Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can python objects have nested properties?

Tags:

python

object

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?

like image 413
user1876508 Avatar asked Jul 29 '13 01:07

user1876508


People also ask

What is nested object in Python?

In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary.

Does Python allow nested classes?

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.

What are Python object properties?

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.


1 Answers

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
like image 120
qwwqwwq Avatar answered Sep 23 '22 15:09

qwwqwwq