I'd like to be able to define a class variable (in the base class somehow) that is present but not shared among the subclasses or instances. What I initially tried was the following:
from __future__ import print_function # For lambda print()
class CallList(list):
def __call__(self, *args, **kwargs):
for f in self:
f(*args, **kwargs)
class State:
on_enter = CallList()
def enter(self):
self.on_enter()
class Opening(State): pass
class Closing(State): pass
Opening.on_enter.append(lambda: print('Opening state entered'))
Closing.on_enter.append(lambda: print('Closing state entered'))
but the behaviour of the subclasses and subclass instances is to reference the base classes class variable, which gives me the following:
opening = Opening()
closing = Closing()
opening.enter()
# Actual output: Opening state entered
# Closing state entered
# Desired output: Opening state entered
opening.on_enter.append(lambda: print('Additional instance callback'))
opening.enter()
# Actual output: Opening state entered
# Closing state entered
# Additional instance callback
# Desired output: Opening state entered
# Additional instance callback
closing.enter()
# Actual output: Opening state entered
# Closing state entered
# Additional instance callback
# Desired output: Closing state entered
I understand why this is happening (I was expecting something different from experience is other languages, but that's fine).
Is is possible to modify the Base class (and not the subclasses) to get the subclasses to each have their own copy of the class variable, and for the instances of the subclasses to get a copy of their classes variable that can then independently be modified with no sharing as well?