我有一个对象定义如下
class a():
@property
def prop(self):
print("hello from object.prop")
@property
def prop1(self):
print("Hello from object.prop.prop")
Run Code Online (Sandbox Code Playgroud)
我打电话的时候
>>> obj = a()
>>> obj.prop
hello from object.prop
>>> obj.prop.prop
Run Code Online (Sandbox Code Playgroud)
我收到以下回溯错误
Traceback (most recent call last):
File "object_property.py", line 13, in <module>
a.prop.prop1
AttributeError: 'NoneType' object has no attribute 'prop1'
Run Code Online (Sandbox Code Playgroud)
我想弄清楚的是我是否可以为对象定义嵌套属性?
回溯是因为你的属性没有return语句,因此返回NoneType,显然不能拥有自己的属性.您的属性可能需要返回具有其自己prop属性的其他类的实例.像这样的东西:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5906 次 |
| 最近记录: |