2017-05-17 21 views
1

這裏失蹤(不能自動傳遞)是我的代碼:的Python: '自我' 在對象

from xml.etree.ElementTree import ElementTree 
from xml.etree.ElementTree import Element 
import xml.etree.ElementTree as etree 
import os 

class Accounts: 
    def __init__(self): 
     self.file_path = os.path.join('lib', 'accounts.xml') 

    def get(self, key, value): 
     tree = ElementTree.parse(self.file_path) 
     print(tree) 

accounts = Accounts 
accounts.get('k', 'v') 

我得到這個錯誤:

Traceback (most recent call last): 
    File ".\XML_Build.py", line 15, in <module> 
    accounts.get('k', 'v') 
TypeError: get() missing 1 required positional argument: 'value' 

當我使用accounts.get(key='k', value='v'),錯誤說我失蹤'self'。我從來沒有見過這個問題。我如何通過自我?我認爲它是自動傳遞的。

回答

2

你應該創建一個實例:

accounts = Accounts() # parenthesis added 

否則,你訪問類(它的行爲像一個正常的Python函數)的方法,而不是在實例(其中自隱式傳遞)。

2

您設置accounts成爲Accounts類的別名,但你需要初始化它作爲一個實例賬戶

accounts = Accounts() 

否則,它被稱爲靜態方法,因此沒有可以通過的「自我」(因爲self總是該類的一個實例)