Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

You want:

@classmethod
def save_from_row(cls, row):

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top