在派生自 uuid.UUID 的自定义 class 中设置属性:AttributeError

Set attribue in custom class derived from uuid.UUID: AttributeError

我正在将一些代码从 IronPython 移植到 CPython (3.8) + Python.NET 并且我有一个自定义的 class 以一种奇怪的方式被破坏:它给了我一个 AttributeError即使该成员出现在 __dict__ 中。此 class 源自 uuid.UUID 以添加对 BLE 短 UUID 的支持:

import uuid

class UUID(uuid.UUID):
    """Represents a more general version of the uuid.UUID, so we can have both
            regular and short UUIDs.
    """

    def __init__(self, hex=None, bytes=None, is_short=False, **kwargs):
        try:
            super(UUID, self).__init__(hex=hex, bytes=bytes, **kwargs)
            self.__dict__['is_short'] = False
        except ValueError as val_ex:
            if hex is None or len(hex) != 4:
                raise val_ex

            # Remove braces GUIDs 
            hex_digits = hex.strip('{}').replace('-', '')

            # remove RFC 4122 URN's 'urn:uuid:deadbeef-1234-fedc-5678-deadbeefaaaa'
            hex_digits = hex_digits.replace('uuid:', '').replace('urn:', '')

            if len(hex_digits) != 4:
                raise ValueError('badly formed hexadecimal UUID string')
            self.__dict__['int'] = int(hex, 16)
            self.__dict__['is_short'] = True

        if is_short is True:
            self.__dict__['is_short'] = True

    def __str__(self):
        if self.is_short:
            hex = '%04x' % self.int
            return '%s' % (hex[:4])
        else:
            return super(UUID, self).__str__()

我是这样使用它的:

class Test_UUID(unittest.TestCase):
    def test_create(self):
        x = pybletestlibrary.UUID("1800")
        pprint(x.__dict__)
        print(x)

以上代码产生:

{'int': 6144, 'is_short': True}
E
======================================================================
ERROR: test_create (__main__.Test_UUID)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test\test_pybletestlibrary.py", line 27, in test_create
    print(x)
  File "my_uuid.py", line 66, in __str__
    hex = '%04x' % self.int
AttributeError: int
----------------------------------------------------------------------
Ran 1 test in 0.003s

FAILED (errors=1)

我不能使用 setattr() 因为 uuid.UUID 是不可变的。我不明白为什么 AttributeError 作为 int 出现在 __dict__ 中。有什么建议吗?

谢谢!!

我的意思是:

import uuid

class UUID(uuid.UUID):
    """Represents a more general version of the uuid.UUID, so we can have both
            regular and short UUIDs.
    """

    def __init__(self, hex=None, bytes=None, is_short=False, **kwargs):
        self.is_short = False
        if len(hex) == 4:
            self.is_short = True
            hex = "0000"+hex+"-0000-1000-8000-00805f9b34fb"
        super(UUID, self).__init__(hex=hex, bytes=bytes, **kwargs)

    def __str__(self):
        val = super(UUID, self).__str__()
        if self.is_short:
            return val[4:8]
        else:
            return val

您可能还必须覆盖其他一些属性。