Skip to main content
 首页 » 编程设计

Python noob 无法让类方法工作

2025年05月04日12hnrainll

我的 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) 

我不明白参数数量的不匹配。怎么回事?

请您参考如下方法:

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 变体。