Get atributes from a parent class from child in Python 3

Question

I have some Parent and Clild class in Python 3 with some atributes, one of these atributes is the sum between the other.

Parent Class:

class Parent:
    ATRIBUTE1 = 'dad'
    ATRIBUTE2 = ' good'
    ATRIBUTE3 = ATRIBUTE1 + ATRIBUTE2

Child Class:

class Child(Parent):
    ATRIBUTE1 = 'son'
    ATRIBUTE2 = ' bad'

I just want inherit the ATRIBUTE3 in the Child Class with the same properties.

Expected output:

>> parent.ATRIBUTE3
'dad good'

>> child.ATRIBUTE3
'son bad'

Show source
| class   | python   | python-3.x   | inheritance   2017-01-07 12:01 2 Answers

Answers to Get atributes from a parent class from child in Python 3 ( 2 )

  1. 2017-01-07 12:01

    You need a property.

    class Parent:
        ATRIBUTE1 = 'dad'
        ATRIBUTE2 = ' good'
    
        @property
        def attribute3(self):
            return self.ATRIBUTE1 + self.ATRIBUTE2
    

    Now parent.attribute3 and child.attribute3 will give you the result you want.

  2. 2017-01-07 12:01

    ATTRIBUTE3 is evaluated at class creation time, and not recalculated on every access. Therefore you inherit parent's value, not formula.

    If you wish attribute value recalculated on every access you can use @property:

    class Parent:
        ATRIBUTE1 = 'dad'
        ATRIBUTE2 = ' good'
    
        @property
        def ATRIBUTE3(self):
            return self.ATRIBUTE1 + self.ATRIBUTE2
    

    And you can access it the same way as before (though read only):

    print(child.ATTRIBUTE3)
    

Leave a reply to - Get atributes from a parent class from child in Python 3

◀ Go back