Is there a way to set attribute to sub objects in a class?

64 views Asked by At

I would like to be able to do this:

>>> obj = Example('hi', 'hello')
>>> obj.a 
'hi'
>>> obj.sub_obj.b
'hello'

I try this but I get AttributeError: 'dict' object has no attribute 'b':

class Example:
    def __init__(self, a, b):
        self.a = a
        self.sub_obj = {} 
        self.sub_obj.b = b

I see a similar question but I don't understand much: Can python objects have nested properties?. I just want the output JSON is to have nested objects. The API requires me to do so.

2

There are 2 answers

7
Barmar On BEST ANSWER

The attribute is a dictionary, so assign to its keys the normal way, with [] syntax.

class Example:
    def __init__(self, a, b):
        self.a = a
        self.sub_obj = {'b': b} 

    def update_b(self, new_b):
        self.sub_obj['b'] = new_b
2
Zuriel Zárate García On

Objects created by literal syntax will continue to be of the vanilla type and won't have your new methods/attributes.