Python. Define "attribute initial method"
I have:
class C:
aaa=2
class B:
def __init__ (self,name):
self.name
self.value
How can i define class C
so when i dynamically set attribute to instance it make that attribute instance of class B
. And attribute name of class B
have to have attribute name
equal string of name of that new attribute in cla开发者_开发问答ss C
and attribute value
of B
instance have to have value what set in new attribute in instance of class C
.
Have to give me that result:
>> c=C()
>> c.whatever= 'strinstrinsstring'
>> isinstance(c.whatever,B)
True
>> c.whatever.value
'strinstrinsstring'
>>c.whatever.name
'whatever'
Just smartly override __setattr__
. If you want to do it only for a specific attribute, then put in a special case for the attribute name that you want to look for:
>>> 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 you want it for every attribute, just forget the if
and it'll do it for everything:
>>> 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?'
This is a horrible thing to do, because it changes what attributes mean!
Why not just look at the __dict__
of c
:
>>> class C(object):
... pass
...
>>> c = C()
>>> c.spam = 'ham'
>>> c.__dict__
{'spam': 'ham'}
精彩评论