Python noob can't get class method to work

后端 未结 2 604
孤街浪徒
孤街浪徒 2021-01-27 02:31

I have a method in my Customer class called save_from_row(). It looks like this:

@classmethod
def save_from_row(row):
    c = Customer(         


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-27 02:53

    The first argument to a classmethod is the class itself. Try

    @classmethod
    def save_from_row(cls, row):
        c = cls()
        # ...
        return c
    

    or

    @staticmethod
    def save_from_row(row):
        c = Customer()
        # ...
        return c
    

    The classmethod variant will enable to create subclasses of Customer with the same factory function.

    Instead of the staticmethod variant, I'd usually use module-level functions.

提交回复
热议问题