Overriding class function with instance function in python [duplicate]
Consider this example:
class master:
@classmethod
def foo(cls):
开发者_StackOverflow 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!
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.
精彩评论