Dan smith Dan smith - 9 months ago 98
Python Question

Python: change parent class property from child class

In python (v3.6.1), I am looking to write a class like this:

class SecondClass(FirstClass):
property = "custom"

print(SecondClass.name) #=> "john"

class SecondClass(FirstClass):
property = "notcustom"

print(SecondClass.name) #=> "steve"


I have tried to set up the
FirstClass
class like this:

class FirstClass:
if property == "custom":
name = "john"
else:
name = "steve"


But I don't seem to be able to edit the property of the
FirstClass
from the SecondClass.

Is this possible?

Answer Source

Since you're using Python 3.6, you can accomplish what your asking by using the new __init_subclass__ method. From the documentation on __init_subclass__:

This method is called whenever the containing class is subclassed. cls is then the new subclass. If defined as a normal instance method, this method is implicitly converted to a class method.

class FirstClass:
    def __init_subclass__(cls):
        super().__init_subclass__()
        if cls.property == "custom":
            cls.name = "john"
        else:
            cls.name = "steve"

class SecondClass(FirstClass):
    property = "custom"

print(SecondClass.name)

class SecondClass(FirstClass):
    property = "notcustom"

print(SecondClass.name) 

For a method that works with Python 3.5 and lower, you can use some Meta class magic:

class FirstClass(type):
    def __init__(cls, name, bases, attrs):
        if cls.property == "custom":
            cls.name = "john"
        else:
            cls.name = "steve"
        super(FirstClass, cls).__init__(name, bases, attrs)

class SecondClass(metaclass=FirstClass):
    property = "custom"

print(SecondClass.name)

class SecondClass(metaclass=FirstClass):
    property = "notcustom"

print(SecondClass.name)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download