python中的动态方法绑定

2024-09-27 07:24:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下两门课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

Tags: 方法returndefsomepassdomethodsomething
1条回答
网友
1楼 · 发布于 2024-09-27 07:24:17

这很简单,只要确保在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

相关问题 更多 >

    热门问题