我想在Python中创建和设置属性属性的值。
以下是一个例子:
book = Dynamic()
book.chapter1.section2 = 'abc'
我的book对象没有chapter1属性,因此必须在调用 setattr 时创建它。我已经开始工作了:
book = Dynamic()
book.chapter1 = SubDynamic()
book.chapter1.section2 = 'section 2'
但是,我不能弄清楚如何将它连接到一行而不会出现错误,告诉我chapter1不存在。
这就是我所拥有的。
class Dynamic(object):
def __setattr__(self, name, value):
sn = SubDynamic(value)
self.__dict__[name] = v
class SubDynamic(object):
def __init__(self, attr):
value = ""
self.attr = value
def __setattr__(self, name, value):
self.__dict__[name] = value
if __name__ == '__main__':
book = Dynamic()
book.chapter1.section2 = 'abc'
答案 0 :(得分:5)
我认为你可以通过实施__getattr__
来简化这一点:
class Dynamic(object):
def __getattr__(self, name):
sub = Dynamic()
setattr(self, name, sub)
return sub
>>> book = Dynamic()
>>> book.chapter1.section2 = 'abc'
>>> book.chapter1
<test.Dynamic object at 0x7feb0f697910>
>>> book.chapter1.section2
'abc'