我有:
class C:
aaa=2
class B:
def __init__ (self,name):
self.name
self.value
如何定义类C
所以当我动态地将属性设置为实例时,它会创建类B
的属性实例。类B
的属性名称必须具有属性name
等于该类C
中该新属性的名称字符串,并且value
实例的属性B
必须具有在类C
的实例中在新属性中设置的值。
必须给我这个结果:
>> c=C()
>> c.whatever= 'strinstrinsstring'
>> isinstance(c.whatever,B)
True
>> c.whatever.value
'strinstrinsstring'
>>c.whatever.name
'whatever'
答案 0 :(得分:5)
巧妙地覆盖__setattr__
。如果您只想为特定属性执行此操作,请为要查找的属性名称添加特殊大小写:
>>> class B:
def __init__(self, name, value):
self.name = name
self.value = value
>>> class C:
def __setattr__(self, name, value):
if name == 'makeMeB':
newb = B(name, value)
self.__dict__[name] = newb
else:
self.__dict__[name] = value
>>> c = C()
>>> c.makeMeB = 'foo'
>>> isinstance(c.makeMeB, B)
True
>>> c.makeMeB.name
'makeMeB'
>>> c.makeMeB.value
'foo'
>>> c.blah = 'foo'
>>> isinstance(c.blah, B)
False
如果您想要每个属性,只需忘记if
,它就会为所有内容做到这一点:
>>> class B:
def __init__(self, name, value):
self.name = name
self.value = value
>>> class C:
def __setattr__(self, name, value):
attr_as_b = B(name, value)
self.__dict__[name] = attr_as_b
>>> c = C()
>>> c.makeMeB = 'foo'
>>> isinstance(c.makeMeB, B)
True
>>> c.makeMeB.name
'makeMeB'
>>> c.makeMeB.value
'foo'
>>> c.amIalsoB = 'well?'
>>> isinstance(c.amIalsoB, B)
True
>>> c.amIalsoB.name
'amIalsoB'
>>> c.amIalsoB.value
'well?'
答案 1 :(得分:1)
这是一件可怕的事情,因为它改变了属性的含义!
为什么不看__dict__
的{{1}}:
c