在python中使用类方法

时间:2017-04-26 04:12:12

标签: python oop class-method

我有一个方法工作正常,但我希望它是一个类方法,但是当我使用@classmethod装饰器时,我得到一个错误,表明我缺少一个参数(至少我理解)

这是工作代码及其结果:

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'

我无法找到错误的原因。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您的类方法应具有此类签名。

@classmethod
def get_collection(cls, conditional_str):

clsself不同,因为它引用了该类,即Entity

因此,您致电

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

,您可以致电

cls.get_subset_from_persistant(cls.__name__, conditional_str)