Python如何支持与运行时多态性相关的常见问题?

2024-05-19 21:38:04 发布

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

我试图执行下面的代码,但我得到错误

class base:

    def callme(data):
        print(data)


class A(base):

    def callstream(self):
        B.stream(self)

    def callme(data):
        print("child ", data)


class B:

    def stream(data):
     # below statement doesn't work but I want this to run to achieve run time 
     # polymorphism where method call is not hardcoded to a certain class reference.
     (base)data.callme("streaming data")

     # below statement works but it won't call child class overridden method. I 
     # can use A.callme() to call child class method but then it has to be 
     # hardcoded to A. which kills the purpose. Any class A or B or XYZ which 
     # inherits base call should be able to read stream data from stream class. 
     # How to achive this in Python? SO any class should read the stream data as 
     # long as it inherits from the base class. This will give my stream class a 
     # generic ability to be used by any client class as long as they inherit 
     # base class.
     #base.callme("streaming data")


def main():
    ob = A()

    ob.callstream()


if __name__=="__main__":
    main()

Tags: thetochilddatabasestreamdefas
1条回答
网友
1楼 · 发布于 2024-05-19 21:38:04

根据问题中的代码,我用以下代码得到了您所说的(在注释中而不是在问题tsk,tsk中)要查找的输出:

class base:

    def callme(self, data):
        print(data)


class A(base):

    def callstream(self):
        B.stream(self)

    def callme(self, data):
        print("child", data)


class B:
    @classmethod
    def stream(cls, data):
        data.callme("streaming data")


def main():
    ob = A()

    ob.callstream()


if __name__=="__main__":
    main()

基本上,我只是确保实例方法具有self参数,而且由于您似乎将B.stream()用作类方法,因此我将其声明为类方法

相关问题 更多 >