更新:刚刚
call_user_func_array在您的帖子中看到了对它的引用。那不一样。用于
getattr获取函数对象,然后使用您的参数调用它
class A(object): def method1(self, a, b, c): # foomethod = A.method1
method现在是一个实际的函数对象。可以直接调用(函数是python中的一流对象,就像PHP>
5.3中一样)。但是下面的考虑仍然适用。也就是说,除非您
A.method1使用下面讨论的两个装饰器中的一个进行装饰,将其
A作为第一个参数传递给实例或在的实例上访问方法,否则以上示例将爆炸
A。
a = A()method = a.method1method(1, 2)
您有三种选择
- 使用的实例
A
进行呼叫method1
(使用两种可能的形式) - 将
classmethod
装饰器应用于method1
:您将不再能够引用其中self
,method1
但在这种情况下,您将cls
在该位置传递一个实例A
。 - 在应用
staticmethod
装饰器method1
:您将不再能够引用self
,或cls
在staticmethod1
但你可以硬编码到引用A
到它,但很明显,这些文献将被所有子类继承A
,除非他们专门覆盖method1
,不叫super
。
一些例子:
class Test1(object): # always inherit from object in 2.x. it's called new-style classes. look it up def method1(self, a, b): return a + b @staticmethod def method2(a, b): return a + b @classmethod def method3(cls, a, b): return cls.method2(a, b)t = Test1() # same as doing it in another classTest1.method1(t, 1, 2) #form one of calling a method on an instancet.method1(1, 2) # form two (the common one) essentially reduces to form oneTest1.method2(1, 2) #the static method can be called with just argumentst.method2(1, 2) # on an instance or the classTest1.method3(1, 2) # ditto for the class method. It will have access to the classt.method3(1, 2) # that it's called on (the subclass if called on a subclass)# but will not have access to the instance it's called on# (if it is called on an instance)
请注意,就像
self变量名完全取决于您一样,变量名也完全取决于您,
cls但这些是常规值。
现在您知道该怎么做了,我会认真考虑 是否 要这样做。通常,本应被称为未绑定(无实例)的方法最好保留为python中的模块级函数。



