2010-10-04 188 views
24

在Python中,有沒有辦法從另一個類調用一個類方法?我試圖在Python中旋轉我自己的MVC框架,我無法弄清楚如何從另一個類中的一個類調用方法。從另一個類調用類方法

以下是我想發生:

class A: 
    def method1(arg1, arg2): 
     # do code here 

class B: 
    A.method1(1,2) 

我慢慢進入Python從PHP所以我找了Python相當於PHP的call_user_func_array()的。

+0

這是否真的需要一個類的方法,而不是一個功能?其他語言的靜態方法不一定映射到Python中的類方法。給這個讀:http://dirtsimple.org/2004/12/python-is-not-java.html – 2010-10-04 15:09:32

+5

@Ivo老實說,如果他在學習基礎之前編寫自己的MVC,你會關心什麼?讓他嘗試並學習過程中的基礎知識。退出對提問人員的尊重。 – aaronasterling 2010-10-04 15:38:47

+4

@AaronMcSmooth這是誠實的建議 - 他目前的問題甚至沒有一個明智的答案,因爲它沒有任何意義,這是經常發生的事情。我試圖寫一個答案,但我只能建議先學習python基礎知識。我會在下次添加一些「很好的」;) – 2010-10-04 15:47:27

回答

33

更新:剛剛在您的帖子中看到了對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) 

你有這樣做的

  1. 使用的A實例method1(使用兩種可能的形式)來調用
  2. classmethod裝飾適用於method1三個選項:你會不會更長的時候可以參考selfmethod1,但是您會在的地方通過cls實例在這種情況下爲。
  3. 應用staticmethod裝飾到method1:您將不再能夠引用self,或clsstaticmethod1但你可以硬編碼到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中的模塊級函數。

+0

'@classmethod 中cls的含義def method3(cls,a,b): return cls.method2(a,b)' – 2018-02-06 04:39:32

4

只是把它和供應self

class A: 
    def m(self, x, y): 
     print(x+y) 

class B: 
    def call_a(self): 
     A.m(self, 1, 2) 

b = B() 
b.call_a() 

輸出:3

+0

這個例子是錯誤的,因爲您正在將B類引用傳遞給A類方法 – 2017-11-21 16:59:21

+0

I只要所有在方法中被稱爲self.x的屬性都存在於B @ – a1an 2018-03-06 15:46:40

+0

@VarunMaurya中,Python就會使用鴨子打字,所以不會檢查類。正如a1an所說,只要你提供了一個具有正確屬性的對象,就可以工作。 – ratiotile 2018-03-07 22:50:46