python中的动态方法绑定

时间:2019-01-16 04:16:15

标签: python polymorphism

我具有以下两个类A和B。如何使do_someting()方法在B中调用重写方法some_method()。这在Python中可行吗?

class A:
    @staticmethod
    def some_method()
        # pass
        return

    @classmethod
    def do_something():
        A.some_method()
        ...
        return

class B(A):
    @staticmethod
    def some_method()
        # how does do_something call here?
        return

    @classmethod
    def run()
        B.do_something()
        return

1 个答案:

答案 0 :(得分:1)

这非常简单,只需确保在selfcls中修复冒号即可:

class A:
    @staticmethod
    def some_method():
        # pass
        return

    @classmethod
    def do_something(cls):
        cls.some_method()
        return

class B(A):
    @staticmethod
    def some_method():
        print("I did stuff!")
        return

    @classmethod
    def run(cls):
        B.do_something()
        return

k = B()
k.run()
>>>"I did stuff!"

如果您要从B类调用旧的do_something(A类中的那个),只需传入相应的类即可。在B类中:

@classmethod
def run(cls):
    A.do_something()
    return