我知道SO社区有多激烈,所以我会尽我所能保留这个问题minimal, complete and verifiable。在
我只想知道monkey patching是否可以用来代替现有函数的定义?在
例如:
class A():
def foo():
print '2'
def foo():
print '5'
A.foo = foo
这种方式似乎也不起作用,为什么我不只是添加一个新函数而不是替换一个现有函数,我在其他类中调用这些函数,我的理解是monkey patching在运行时添加了这些函数,我需要我的python代码在apachespark服务器上运行,这会抛出一个错误,认为对该函数的调用未被引用。在
所以请友好点,帮我解决问题或者建议一个解决办法。 谢谢。在
编辑:代码的目标是在调用A.foo时打印5。在
您唯一的问题是您没有正确定义
foo
。它需要为调用它的实例提供一个显式参数。在从一个非常真实的意义上讲,monkey-patching首先就是类的创建方式。
^{pr2}$class
语句几乎只是以下代码的语法糖分:把
type
的定义想象成类似于我希望我能理解你在这里想做什么。这在python3中是可行的:
但是在python2中有几个注意事项。在
print
不是Python3中的方法(请参见此处:Why doesn't print work in a lambda?)您不能只调用未绑定的消息(请参见此处:In Python, can you call an instance method of class A, but pass in an instance of class B?)
所以你必须这样做:
^{pr2}$编辑: 在看到你在评论中的问题后,我想你其实想要一些不同的东西。这是:
这在python2中工作得很好。在
self
是对方法绑定到的当前实例的引用。当您只是调用诸如print
之类的访问附加到该实例的任何属性或方法的东西时,不使用它。但对于不同的情况,请看以下示例:同样正如切普纳在其帖子下的评论中指出的:
相关问题 更多 >
编程相关推荐