2014-10-05 72 views
-1

我來自C/C++世界,我很難在python中做所有的OOP類比。我裹着我的腳本中的一類,現在在我log()「私人」的實例方法得到這個錯誤:如何在python實例方法中創建靜態局部變量?

​​

def __log(self, contents):             
    sys.stdout.write(contents)            

    # Append all writes after the first          
    if not hasattr(self.__log, "counter"):         
     self.__log.counter = 1            
     f = open(self.output_filepath, 'w')         
    else :                 
     f = open(self.output_filepath, 'a')         

    f.write(contents)              
    f.close() 
+1

我強烈建議您不要使用「私人」名稱,如「__log」。它們很醜,並且實際上並沒有阻止訪問。 Python的工作方式與C++不同。爲了自己的利益使用它。 – 2014-10-05 18:21:59

+0

雖然他們是一個非常強大的「停止」標誌。作爲主要Python庫的共同開發者,我可以告訴你使用下劃線向用戶發出接口/實現邊界的信號是多麼重要。 – 2014-10-05 18:45:10

+0

很好,使用單個下劃線。雙下劃線只是說,「我習慣於Java或C++,並希望我的私人關鍵字回來!」 – 2014-10-05 23:30:48

回答

-1

Python沒有靜態局部變量。你想要什麼是最好的解決方法是使用一個類屬性:

class WithLog(object): 

    opened = False 

    def log(self, contents):             
     sys.stdout.write(contents)            

     mode = "a" if self.__class__.opened else "w" 
     with open(self.output_filepath, mode) as f: 
      f.write(contents)  

     self.__class__.opened = True 

當然,它可能是最好不要經常打開和關閉日誌文件....

+0

感謝您展示'with'關鍵字! – tarabyte 2014-10-05 18:39:37

1

self.__log.counter引用到counter變量,不會在__log方法存在。

如果你需要counter變量爲對象的實例的一部分,如果你需要counter是靜態的類通過self.counter

提到它,定義之外的任何類定義的變量方法。檢查this SO質疑

如果你真的真的需要counter變量是實例方法,引用它是這樣的一部分通過ClassName.__log.counter

一個很好的開始學習面向對象的概念在Python將蟒蛇文檔。 https://docs.python.org/2/tutorial/classes.html

-1

這你不能將屬性添加到方法,但可以修改其字典屬性:

class Test: 
    def __log(self, contents):             
     sys.stdout.write(contents)            

     # Append all writes after the first          
     if not "counter" in self.__log.__func__.__dict__:         
      self.__log.__func__.__dict__["counter"]= 1            
      f = open(self.output_filepath, 'w') 
      print 'w'        
     else :                 
      f = open(self.output_filepath, 'a') 
      print 'a'        

     f.write(contents)              
     f.close() 

a = Test() 
a._Test__log('') #Prints w 
a._Test__log('') #Prints a 
b = Test() 
b._Test_log('') #Prints a 
+0

請檢查編輯並讓我知道如果這是你想要的 – 2014-10-05 18:13:51

+0

有人可以解釋我的答案有什麼問題嗎? – 2014-10-05 18:27:13

+0

向函數添加屬性很愚蠢。 Python沒有靜態局部變量,你不應該試圖強制它們。相反,想出一個解決這個問題的Python解決方案。 – 2014-10-05 18:28:24