2017-04-26 61 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中使用类方法 –