【发布时间】:2021-10-26 03:33:50
【问题描述】:
对于我正在进行的项目,我希望能够将名称与对象相关联。我想这样做的方法是将对象的 .name 属性设置为我想要的名称。我真正需要的是一个函数,它接受一个对象的实例,并返回在各方面都相同但具有 .name 属性的东西。问题是我不知道对象将是什么类型的数据,所以我不能使用子类化例如
我尝试过的每种方法都遇到了问题。试图直接给它一个 .name 属性是行不通的,例如:
>>> cats = ['tabby', 'siamese']
>>> cats.name = 'cats'
Traceback (most recent call last):
File "<pyshell#197>", line 1, in <module>
cats.name = 'cats'
AttributeError: 'list' object has no attribute 'name'
使用 setattr 也有同样的问题。
我尝试创建一个新类,该类在 init 上复制实例中的所有属性,并且还有一个 .name 属性,但这也不起作用。如果我尝试:
class NamedThing:
def __init__(self, name, thing):
thing_dict = {#not all types have a .__dict__ method
name: getattr(thing, name) for name in dir(thing)
}
self.__dict__ = thing_dict
self.name = name
它复制 dict 没有问题,但由于某种原因,除非我直接调用新方法,否则 python 无法找到它们,因此该对象失去了所有功能。例如:
>>> cats = ['tabby', 'siamese']
>>> named_thing_cats = NamedThing('cats', cats)
>>> named_thing_cats.__repr__()#directly calling .__repr__()
"['tabby', 'siamese']"
>>> repr(named_thing_cats)#for some reason python does not call the new repr method
'<__main__.NamedThing object at 0x0000022814C1A670>'
>>> hasattr(named_thing_cats, '__iter__')
True
>>> for cat in named_thing_cats:
print(cat)
Traceback (most recent call last):
File "<pyshell#215>", line 1, in <module>
for cat in named_thing_cats:
TypeError: 'NamedThing' object is not iterable
我也试过直接设置class来设置类型和属性:
class NamedThing:
def __init__(self, name, thing):
thing_dict = {#not all types have a .__dict__ method
name: getattr(thing, name) for name in dir(thing)
}
self.__class__ = type('NamedThing', (type(thing),), thing_dict)
self.name = name
但这会遇到问题,具体取决于事物的类型:
>>> cats = ['tabby', 'siamese']
>>> named_thing_cats = NamedThing('cats', cats)
Traceback (most recent call last):
File "<pyshell#217>", line 1, in <module>
named_thing_cats = NamedThing('cats', cats)
File "C:/Users/61490/Documents/Python/HeirachicalDict/moduleanalyser.py", line 12, in __init__
self.__class__ = type('NamedThing', (type(thing),), thing_dict)
TypeError: __class__ assignment: 'NamedThing' object layout differs from 'NamedThing'
我真的被困住了,帮助会很棒
【问题讨论】:
标签: python properties attributes