Suppose I have the following classes
class Parent:
message = "Hello World"
@classmethod
def print_message(cls):
print(cls.message)
@classmethod
def change_message(cls, new_message):
cls.message = new_message
class Child_one(Parent):
@classmethod
def print_messsage(cls):
print (cls.message)
@classmethod
def change_message(cls, new_message):
cls.message = new_message
class Child_two(Parent):
@classmethod
def print_message(cls):
print(cls.message)
I suppose my question is to what does the cls of child classes refer to, because If I change the static variable message in parent class it rightly changes values of the of message in both children
Parent.change_message("This is new message")
Child_one.print_message() # This is new message
Child_two.print_message() # This is new message
this is my expected behavior, both of the cls.message refer to the message of parent class. However doing this
Child_one.change_message("I am child one")
results in behavior such as
Parent.print_message() # This is new message
Child_one.print_message() # I am child one
Child_two.print_message() # This is new message
So the cls.message variable of Child_one no longer points to the message of the parent class.
In other langues such as c++ or c# static changing a static variable of a parent class or a child class results in change in all of the parent and derived classes. Is there a way to duplicate this behavior in python and if not why not?