2017-04-26 23 views
0

我有一個方法可以正常工作,但我希望它是一個類方法,但是當我使用@classmethod裝飾器時,出現一個錯誤,指出我缺少一個參數(在至少據我所知)在python中使用類方法

這是工作的代碼和它的結果:

company=Company() 
company_collection=company.get_collection('') 
for scompany in company_collection: 
    print(scompany.get_attrs()) 

class Entity(Persistent): 

    def get_collection(self, conditional_str): 
     subset=[] 
     collection=[] 
     subset=self.get_subset_from_persistant(self.__class__.__name__, conditional_str) 
     for entity in subset: 
      collection.append(self.get_new_entity(entity)) 

     return(collection) 

class Company(Entity): 
    pass 

MacBook-Pro-de-Hugo:Attractora hvillalobos$ virtual/bin/python3 control.py 
{'id': '1', 'razon_social': 'Attractora S.A. de C.V.', 'rfc': ' xxxxxxxx'} 
{'id': '2', 'razon_social': 'Otra empresa sa de cv', 'rfc': ' yyyyyyyy'} 
{'id': '3', 'razon_social': 'Una mas sa de vc', 'rfc': ' zzzzz'} 

這失敗的一個,其結果是:

company_collection=Company.get_collection('') 
for scompany in company_collection: 
    print(scompany.get_attrs()) 

class Entity(Persistent): 

    @classmethod 
    def get_collection(self, conditional_str): 
     subset=[] 
     collection=[] 
     subset=self.get_subset_from_persistant(self.__class__.__name__, conditional_str) 
     for entity in subset: 
      collection.append(self.get_new_entity(entity)) 

     return(collection) 

class Company(Entity): 
    pass 

MacBook-Pro-de-Hugo:Attractora hvillalobos$ virtual/bin/python3 control.py 
Traceback (most recent call last): 
    File "control.py", line 14, in <module> 
    company_collection=Company().get_collection('') 
    File "/Users/hvillalobos/Dropbox/Code/Attractora/model.py", line 31, in get_collection 
    subset=self.get_subset_from_persistant(self.__class__.__name__, conditional_str) 
TypeError: get_subset_from_persistant() missing 1 required positional argument: 'conditional_str' 

我找不到的原因錯誤。

回答

0

當您定義類方法時,第一個參數應該是cls而不是self。然後,當你從同一個班級打電話時,你只需要做self. get_subset_from_persistant(conditional_str)

在調用類的方法時,您永遠不需要提供clsself參數。

試試這個:

class Entity(Persistent): 

    @classmethod 
    def get_collection(cls, conditional_str): 
     subset=[] 
     collection=[] 
     subset=self.get_subset_from_persistant(conditional_str) 
     for entity in subset: 
      collection.append(self.get_new_entity(entity)) 

     return(collection) 

class Company(Entity): 
    pass 
0

你的類方法應該有這種類型的簽名。

@classmethod 
def get_collection(cls, conditional_str): 

clsself不同,因爲它是指類,即Entity

Therfore,你會呼叫

self.get_subset_from_persistant(self.__class__.__name__, conditional_str) 

,而不是,你會打電話

cls.get_subset_from_persistant(cls.__name__, conditional_str) 
+0

有什麼錯誤?爲什麼你想要使它成爲一種類方法? – EyuelDK

+0

我得到了與變更前完全相同的錯誤:「get_subset_from_persistant()缺少1所需的位置參數:'conditional_str'」。我想這樣,因爲我正在學習在Python中使用類方法 –