python 对象可以有嵌套的属性吗? [英] Can python objects have nested properties?
本文介绍了python 对象可以有嵌套的属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象定义如下
class a():@财产定义道具(自我):打印(来自object.prop的你好")@财产def prop1(self):print("你好来自 object.prop.prop")
当我打电话
<预><代码>>>>obj = a()>>>对象道具来自 object.prop 的问候>>>obj.prop.prop我收到以下回溯错误
回溯(最近一次调用最后一次):文件object_property.py",第 13 行,在 <module> 中.a.prop.prop1AttributeError: 'NoneType' 对象没有属性 'prop1'
我想弄清楚是否可以为对象定义嵌套属性?
解决方案
回溯是因为你的属性没有 return
语句,因此它返回 NoneType
,这显然不能有自己的属性.您的属性可能需要返回不同类的实例,该类具有自己的 prop
属性.像这样:
class a():def __init__(self):self.b = b()@财产定义道具(自我):打印(来自object.prop的你好")回归自我.bb类():@财产定义道具(自我):print("你好来自 object.prop.prop")x = a()打印 x.prop.prop>>来自 object.prop 的问候>>你好来自 object.prop.prop>>没有任何
I have an object defined as follows
class a():
@property
def prop(self):
print("hello from object.prop")
@property
def prop1(self):
print("Hello from object.prop.prop")
When I call
>>> obj = a()
>>> obj.prop
hello from object.prop
>>> obj.prop.prop
I get the following traceback error
Traceback (most recent call last):
File "object_property.py", line 13, in <module>
a.prop.prop1
AttributeError: 'NoneType' object has no attribute 'prop1'
What I am trying to figure out is if I can define nested properties for objects?
解决方案
The traceback is because your property doesn't have a return
statement, hence it returns NoneType
, which obviously can't have attributes of its own. Your property would probably need to return an instance of a different class, that has its own prop
attribute. Something like this:
class a():
def __init__(self):
self.b = b()
@property
def prop(self):
print("hello from object.prop")
return self.b
class b():
@property
def prop(self):
print("Hello from object.prop.prop")
x = a()
print x.prop.prop
>> hello from object.prop
>> Hello from object.prop.prop
>> None
这篇关于python 对象可以有嵌套的属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文