Jason Swett
Jason Swett

Reputation: 45094

Python noob can't get class method to work

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?

Upvotes: 1

Views: 557

Answers (2)

Sven Marnach
Sven Marnach

Reputation: 601559

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.

Upvotes: 13

a paid nerd
a paid nerd

Reputation: 31512

You want:

@classmethod
def save_from_row(cls, row):

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

Upvotes: 5

Related Questions