python - 属性错误: 'Employee' object has no attribute 'WorkingHours'

标签 python python-3.x python-2.7 constructor

为什么会出现属性错误?未找到WorkingHours 属性?

class Employee:
    def numberofWorkingHours(self):
        self.WorkingHours = 45

    def printnumberofWorkingHours(self):
        print(self.WorkingHours)

class Trainee:
 def numberofWorkingHours(self):
     self.WorkingHours = 60

emp = Employee()
emp.printnumberofWorkingHours()

最佳答案

class Employee:

    def __init__(self):
        self.WorkingHours = 45

    def printnumberofWorkingHours(self):
        print(self.WorkingHours)

class Trainee:
    def numberofWorkingHours(self):
        self.WorkingHours = 60

emp = Employee()
emp.printnumberofWorkingHours()

将 numberofWorkingHours 方法替换为 __init__

关于python - 属性错误: 'Employee' object has no attribute 'WorkingHours' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50835149/

相关文章:

python - 我将如何创建另一个传入的矩形?

python-2.7 - Python argparse 参数是 python 关键字

python-2.7 - 用唯一的 id 替换 pandas 数据框

python - Python strip( ) 函数出错

python - 如何有效地将多个函数应用于数据框?

python - 我们可以使用 DataContentAdapter 在 plone 表单生成中搜索增值

python - 连接字典中的两个字符串

python - Pygame + Sprite 旋转不保持居中

Python:使用解包元组作为(dict)键的通用方法

python - Pandas 从循环创建数据框