You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python自定义Staff类实例化报TypeError错误求助

问题原因
  1. Python类的魔术方法(内置特殊方法)要求使用前后各两个下划线包裹命名,你代码中的构造方法写为_init_(前后单下划线)、自定义字符串转换方法写为_str_(前后单下划线),Python不会将其识别为类的构造方法和字符串特殊方法,此时类会使用默认的无参构造方法,你实例化时传入3个参数就会触发类型错误。
  2. calculatePay方法中存在变量名拼写错误:你定义第二个提示语时写的是promt(缺了一个字母p),但后续赋值调用的变量名是prompt,运行该方法时会触发变量未定义报错。
修复步骤
  • 将构造方法名从_init_修改为__init__
  • 将字符串特殊方法名从_str_修改为__str__
  • 修正calculatePay中的变量拼写,将promt = "Enter the hourly rate for %s" %(self.name)改为prompt = "Enter the hourly rate for %s" %(self.name)
修复后完整代码
class Staff:
    def __init__(self, pPosition, pName, pPay):
        self.position = pPosition
        self.name = pName
        self.pay = pPay
        print("Creating Staff object.")

    def __str__(self):
        return "Position = %s, Name = %s, Pay = %d" %(self.position, self.name, self.pay)

    def calculatePay(self):
        prompt = "Enter number of hours worked for %s: " %(self.name)
        hours = input(prompt)
        prompt = "Enter the hourly rate for %s: " %(self.name)
        hourlyRate = input(prompt)
        self.pay = int(hours)*int(hourlyRate)
        return self.pay

修复完成后重新运行模块,再执行officeStaff1 = Staff('Basic', 'Yvonne', 0)即可正常实例化对象,调用print(officeStaff1)也会输出你定义的格式化字符串,调用officeStaff1.calculatePay()可以正常计算薪资。

内容的提问来源于stack exchange,提问作者Dibyarka Basu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 20:48:03