【问题标题】:'classmethod' object is not callable [closed]\'classmethod\' 对象不可调用 [关闭]
【发布时间】:2022-08-03 08:21:54
【问题描述】:

我正在做这个练习。 Youtube 上的绅士没有任何问题,但我收到以下错误。谁能给我一条关于如何使用类方法以避免这种情况的建议? 提前致谢。

class Employee:
  def __init__(self,first,last,pay,email):
    self.first=first
    self.last=last
    self.pay=pay
    self.email=email
    
@classmethod
def from_str(cls,emp_str):
    first,last,pay=emp_str.split(\'-\')
    return cls(first,last,int(pay))

new_emp=from_str(Employee,emp_str)

输出:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/9y/ngq521_x3rlc7wgd1c5kwqgh0000gn/T/ipykernel_1551/359192774.py in      <module>
   ----> 1 new_emp=from_str(Employee,emp_str)

TypeError: \'classmethod\' object is not callable

    标签: python class-method


    【解决方案1】:

    from_str 被定义为函数,而不是 Employee 类的方法(注意标识)。所以用@classmethod 装饰它是没有意义的。

    【讨论】:

      猜你喜欢
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 2020-06-27
      • 1970-01-01
      • 1970-01-01
      • 2018-03-27
      相关资源
      最近更新 更多