更新:剛剛在您的帖子中看到了對call_user_func_array
的引用。那不一樣。使用getattr
得到函數對象,然後用你的論點
class A(object):
def method1(self, a, b, c):
# foo
methodname = 'method1'
method = getattr(A, methodname)
method
把它現在是一個實際的函數對象。你可以直接調用(函數是python中的第一類對象,就像在PHP> 5.3中一樣)。但是從下面的考慮仍然適用。也就是說,除非您用下面討論的兩個修飾器之一修飾A.method1
,否則將上述示例炸掉,將A
作爲第一個參數的實例或將getattr
應用於A
的實例。
a = A()
method = getattr(a, methodname)
method(1, 2)
你有這樣做的
- 使用的
A
實例method1
(使用兩種可能的形式)來調用
- 的
classmethod
裝飾適用於method1
三個選項:你會不會更長的時候可以參考self
method1
,但是您會在的地方通過cls
實例在這種情況下爲。
- 應用
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 class
Test1.method1(t, 1, 2) #form one of calling a method on an instance
t.method1(1, 2) # form two (the common one) essentially reduces to form one
Test1.method2(1, 2) #the static method can be called with just arguments
t.method2(1, 2) # on an instance or the class
Test1.method3(1, 2) # ditto for the class method. It will have access to the class
t.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
變量的名稱,但這些是常用的值。
既然你知道如何去做,我會認真考慮如果你想要做。通常情況下,被稱爲unbound(沒有實例)的方法最好作爲python中的模塊級函數。
這是否真的需要一個類的方法,而不是一個功能?其他語言的靜態方法不一定映射到Python中的類方法。給這個讀:http://dirtsimple.org/2004/12/python-is-not-java.html – 2010-10-04 15:09:32
@Ivo老實說,如果他在學習基礎之前編寫自己的MVC,你會關心什麼?讓他嘗試並學習過程中的基礎知識。退出對提問人員的尊重。 – aaronasterling 2010-10-04 15:38:47
@AaronMcSmooth這是誠實的建議 - 他目前的問題甚至沒有一個明智的答案,因爲它沒有任何意義,這是經常發生的事情。我試圖寫一個答案,但我只能建議先學習python基礎知識。我會在下次添加一些「很好的」;) – 2010-10-04 15:47:27