Overriding class function with instance function in python
-
28-10-2019 - |
Question
Consider this example:
class master:
@classmethod
def foo(cls):
cls.bar()
class slaveClass( master ):
@classmethod
def bar(cls):
print("This is class method")
slaveType = slaveClass
slaveType.foo()
class slaveInstance( master ):
#def foo(self):
# self.foo()
def __init__(self,data):
self.data=data
print("Instance has been made")
def bar(self):
print("This is "+self.data+" method")
slaveType = slaveInstance("instance")
slaveType.foo()
I know it works when last definition of foo
is uncommented, but is there any other way to use this foo
function without changing the usage. I have large project where classes defined the way things worked and I was able to change the way with slaveType
but there happen to be a case where instance is needed, and there is bit too many foo
like functions to be overridden for instance behavior.
Thank you stackers!
Solution 2
Okey... I gave my best to preGoogle and figure out what to ask, but I failed. Now I know, that this was what I wanted to do: Creating a method that is simultaneously an instance and class method. There is also the solution I needed.
But it still seems not very beautiful. Maybe there is cleaner way or cleaner hack.
OTHER TIPS
Look closer at the doc for classmethod. Instance methods pass an instance as the first argument, and class methods pass a class as the first argument. Calling slaveType.foo()
passes an instance, slaveType
, as the first argument of foo()
. foo()
is expecting a class as the first argument.