2015-11-08 70 views
1

爲了節省代碼我想在python 3的同一個類中調用另一個方法。不幸的是,我只能得到一個使用固定名稱的對象的解決方案。我的測試代碼應該是自我解釋:調用兄弟方法python3?

import os, sys 

class Window(): 
    konst = "2 ENTERED SECONDMETHOD" 

    def firstMethod(self): 
     print("1 ENTERED FIRSTMETHOD") 

    #Works 
     #But this is not universal 
     windowobj.secondMethod() 

    #Possible solutions that did not work 

     #secondMethod() 
     #NameError: name 'secondMethod' is not defined 

     #__class__.secondMethod() 
     #TypeError: secondMethod() missing 1 required positional argument: 
     #'self' 

     #self.secondMethod() 
     #NameError: name 'self' is not defined 

     #self.__class__.secondMethod() 
     #TypeError: secondMethod() missing 1 required positional argument: 
     #'self' 

     #super().secondMethod() 
     #AttributeError: 'super' object has no attribute 'secondMethod' 

    def secondMethod(self): 
     print(self.konst) 

#Create Object 
windowobj = Window() 

windowobj.firstMethod() 
+0

'self.secondMethod()'應該已經工作了。 – martineau

回答

2

調用self.secondMethod()是正確的方法。

def firstMethod(self): 
    print("1 ENTERED FIRSTMETHOD") 
    self.secondMethod() 

這裏是證明:Ideone online compiler

請不要在它下一次德國人的意見公佈代碼。