Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中向类方法追加/替换实现?_Python_Python 3.x - Fatal编程技术网

如何在Python中向类方法追加/替换实现?

如何在Python中向类方法追加/替换实现?,python,python-3.x,Python,Python 3.x,代码优先: from abc import abstractmethod class SomeInterfaceishClass(): @abstractmethod @staticmethod def foo(bar): pass class SomeClass(SomeInterfaceishClass): @staticmethod def foo(bar): print("implementation here"

代码优先:

from abc import abstractmethod

class SomeInterfaceishClass():
    @abstractmethod
    @staticmethod
    def foo(bar):
        pass

class SomeClass(SomeInterfaceishClass):
    @staticmethod
    def foo(bar):
        print("implementation here")

class EventHandler():
    @staticmethod
    @Multitasking.threaded
    def foo(bar):
        pass
我正在写一个frameworkish的东西,最终用户被迫实现几个方法(为了简单起见,这里只有一个)。因此,我用一个抽象方法定义了SomeInterfaceishClass类。我的问题是,我不会从这个类运行这个方法,相反,我想从EventHandler类运行它。正如您所看到的,它有一个decorator使其异步运行,我认为这就是问题所在

我知道我可以在
SomeInterfaceishClass
的构造函数中调用
EventHandler.foo=getattr(self,'foo')
,但当我这样做时,整个函数将被覆盖(丢失它的装饰器)

我希望让最终用户的代码尽可能干净,因此我不想在
SomeClass
中添加decorator

有没有办法做到这一点?例如,有没有一种方法可以将实现添加到类方法中,而不是将方法添加到类中

只是想澄清一下:我想将它添加到EventHandler类中,而不是它的实例


谢谢大家!:)

我不太清楚你想做什么,或者这是否是个好主意。。。但是如果问题是在设置class属性时装饰器丢失了,那么您可以手动应用装饰器:
EventHandler.foo=staticmethod(Multitasking.threaded(self.foo))
。噢,哇,我不知道staticmethod函数。我可以想象这不是很清楚,但到目前为止,这是一个大项目,并试图保持尽可能干净的例子。无论如何,谢谢你,它似乎已经解决了我的问题:)很乐意帮忙。一般来说,
@something
是函数应用程序的语法糖。你可以用
abstractmethod
classmethod
等做同样的事情。就像我在这里用
staticmethod
做的一样。非常非常非常酷,谢谢你提供的额外信息:)我不太清楚你想做什么,或者这是不是一个好主意。。。但是如果问题是在设置class属性时装饰器丢失了,那么您可以手动应用装饰器:
EventHandler.foo=staticmethod(Multitasking.threaded(self.foo))
。噢,哇,我不知道staticmethod函数。我可以想象这不是很清楚,但到目前为止,这是一个大项目,并试图保持尽可能干净的例子。无论如何,谢谢你,它似乎已经解决了我的问题:)很乐意帮忙。一般来说,
@something
是函数应用程序的语法糖。您可以使用
abstractmethod
classmethod
等做同样的事情。就像我在这里使用
staticmethod
所做的一样。非常非常酷,感谢您提供更多信息:)