【问题标题】:Class constructor raises TypeError类构造函数引发 TypeError
【发布时间】:2013-08-08 07:11:07
【问题描述】:
class employees:
    emp_count = 0

    def _init_(self, name, age):
        self.name = name
        self.age = age
        employees.emp_count += 1

    def displaycounts(self):
        print "total counts is %d" % employee.emp_count

    def displaydetails(self):
        print "Name :", self.name, ",age:", self.age

obj  = employees("krishna",4000)
obj1 = employees("shashi",10000)
obj3 = employees

obj.displaydetails()
obj1.displaydetails()
obj3.displaycounts()

Traceback(最近一次调用最后一次):文件“C:/Python27/dd”,第 14 行, 在 obj = 员工(“克里希纳”,4000) TypeError: 这个构造函数没有参数

【问题讨论】:

  • 它是__init__,开头有两个下划线,结尾有两个下划线!并且:请修正代码的缩进。
  • 现在缩进呢?
  • 还是有点不对劲.. 是 SO 格式问题吗?

标签: python


【解决方案1】:
def __init__(self, name, age):

就是你要找的。​​p>

另外,你必须缩进作为函数的一部分的行,所以

def __init__(self, name, age):
    self.name = name
    self.age = age
    employees.emp_count += 1

更像是...等等,但鉴于您看到的错误,我猜这是堆栈溢出格式问题。

这里还有一些其他问题,但这应该可以帮助您克服当前的障碍。

【讨论】:

  • 实际上错误是 Traceback (最近一次调用最后): File "C:/Python27/dd", line 14, in obj = employees("krishna",4000) TypeError: this constructor takes no论据
  • @user2474432 我认为您会看到该错误,因为默认构造函数不接受任何参数,并且您尝试使用 def _init_(self, name, age): 覆盖它并随后调用 employees('name1', 42)
猜你喜欢
  • 2019-08-14
  • 1970-01-01
  • 2018-06-27
  • 2016-04-16
  • 2021-11-26
  • 2019-10-27
  • 2018-07-18
相关资源
最近更新 更多