开发者

Overriding class function with instance function in python [duplicate]

This question already has an answer here: Creating a method that is simultaneously an instance and class method (1 answer) Closed 2 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜