gpt4 book ai didi

Python noob 无法让类方法工作

转载 作者:太空宇宙 更新时间:2023-11-04 06:46:01 26 4
gpt4 key购买 nike

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

关于Python noob 无法让类方法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4865897/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com