Python:骇客在不属于其类别的物件上呼叫方法 [英] Python: Hack to call a method on an object that isn't of its class
问题描述
假设您定义了一个类,该类具有执行一些复杂处理的方法:
Assume you define a class, which has a method which does some complicated processing:
class A(object):
def my_method(self):
# Some complicated processing is done here
return self
现在您要在另一个类中的某个对象上完全使用该方法。例如,您要执行 A.my_method(7)
。
And now you want to use that method on some object from another class entirely. Like, you want to do A.my_method(7)
.
这是您得到的: TypeError:未绑定方法my_method()必须以实例作为第一个参数(而不是int实例)来调用。。
现在,是否有可能入侵事物,所以您可以在 7
上调用该方法?我想避免移动或重写功能。 (请注意,该方法的逻辑确实取决于 self
。)
Now, is there any possibility to hack things so you could call that method on 7
? I'd want to avoid moving the function or rewriting it. (Note that the method's logic does depend on self
.)
一个说明:我知道有些人会想要这样说:您做错了!您正在滥用Python!您不应该这样做!是的,我知道,这是我想做的一件可怕的事情。我在问是否有人知道该怎么做,而不是向我宣告我不应该这样做。
One note: I know that some people will want to say, "You're doing it wrong! You're abusing Python! You shouldn't do it!" So yes, I know, this is a terrible terrible thing I want to do. I'm asking if someone knows how to do it, not how to preach to me that I shouldn't do it.
推荐答案
当然,我不建议您在实际代码中执行此操作,但是可以,可以,您可以访问类的内部并将其方法用作函数:
Of course I wouldn't recommend doing this in real code, but yes, sure, you can reach inside of classes and use its methods as functions:
class A(object):
def my_method(self):
# Some complicated processing is done here
return 'Hi'
print(A.__dict__['my_method'](7))
# Hi
这篇关于Python:骇客在不属于其类别的物件上呼叫方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!