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?
In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary.
Inner or Nested classes are not the most commonly used feature in Python. But, it can be a good feature to implement code. The code is straightforward to organize when you use the inner or nested classes.
The property() method in Python provides an interface to instance attributes. It encapsulates instance attributes and provides a property, same as Java and C#. The property() method takes the get, set and delete methods as arguments and returns an object of the property class.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With