[PYTHON] Defining a child class property or method does not override the parent class definition

This is also natural ... However, if you are not careful, you may think "that?". For example, consider a class like this.

class A:
    prop1 = 123
    prop2 = prop1
    
    def hoge(self):
        return 'superhoge'
    
    fuga = hoge
    


class SubA(A):
    prop1 = 777
    
    def hoge(self):
        return 'hoge'

When you create a SubA object, hoge () and prop1 will naturally look like this.

>>> a = SubA()
>>> print(a.hoge())
hoge
>>> print(a.prop1)
777

By the way, what about prop2 and fuga? Since they refer to prop1 and hoge respectively, it seems that the same result will be obtained if they are overwritten. However, this is actually the case.

>>> a = SubA()
>>> print(a.fuga())
superhoge
>>> print(a.prop2)
123

From this, we can see that prop2 and fuga refer to the definition of the parent class. As an object-oriented mechanism, the phrase "overwrite with child class" is often used, but it is incorrect. I think you should be careful about how you use words.

Recommended Posts

Defining a child class property or method does not override the parent class definition
Reuse the behavior of the @property method by using a descriptor [16/100]
I implemented a method to calculate the evaluation index (specificity, NPV) that scikit-learn does not have