Python noob can't get class method to work

后端 未结 2 565
孤街浪徒
孤街浪徒 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.

    0 讨论(0)
  • 2021-01-27 03:04

    You want:

    @classmethod
    def save_from_row(cls, row):
    

    Class methods get the method's class as the first argument.

    0 讨论(0)
提交回复
热议问题