Python noob can't get class method to work

烈酒焚心 提交于 2019-12-20 04:15:29

问题


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

@classmethod
def save_from_row(row):
    c = Customer()
    c.name = row.value('customer', 'name')
    c.customer_number = row.value('customer', 'number')
    c.social_security_number = row.value('customer', 'social_security_number')
    c.phone = row.value('customer', 'phone')
    c.save()
    return c

When I try to run my script, I get this:

Traceback (most recent call last):
  File "./import.py", line 16, in <module>
    Customer.save_from_row(row)
TypeError: save_from_row() takes exactly 1 argument (2 given)

I don't understand the mismatch in the number of arguments. What's going on?


回答1:


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.




回答2:


You want:

@classmethod
def save_from_row(cls, row):

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



来源:https://stackoverflow.com/questions/4865897/python-noob-cant-get-class-method-to-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!