如何解决在派生自 uuid.UUID 的自定义类中设置属性:AttributeError
我正在将一些代码从 IronPython 移植到 cpython (3.8) + Python.NET 并且我有一个以奇怪的方式损坏的自定义类:它给了我一个 AttributeError
即使该成员存在于 { {1}}。此类派生自 __dict__
以添加对 BLE 短 UUID 的支持:
uuid.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
中。有什么建议吗?
谢谢!!
解决方法
我的意思是:
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
您可能还需要覆盖其他一些属性。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。