Python新手无法让类方法正常工作

1 投票
2 回答
556 浏览
提问于 2025-04-16 11:01

我在我的 Customer 类里有一个叫 save_from_row() 的方法。它的样子是这样的:

@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

当我尝试运行我的脚本时,我遇到了这个问题:

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)

我不明白参数数量不匹配是怎么回事。发生了什么呢?

2 个回答

5

你想要的是:

@classmethod
def save_from_row(cls, row):

类的方法会把这个方法所属的类作为第一个参数传递进来。

13

第一个参数传给 classmethod 的是类本身。你可以试试

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

或者

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

使用 classmethod 的话,可以用同一个工厂函数来创建 Customer 的子类。

相比于 staticmethod,我通常会使用模块级别的函数。

撰写回答