【问题标题】:How to solve the error "object.__new__() takes no parameters"?如何解决错误“object.__new__() 不带参数”?
【发布时间】:2019-05-03 11:52:38
【问题描述】:

我在运行时遇到这种类型的错误

Traceback (most recent call last):   
  File "C:\Python37-32\python\program\overiding.py", line 17, in <module>
    e1=Employee("Rajesh",9000) 
TypeError: object.__new__() takes no parameters
class Employee:
    def _init_(self, nm=None, sal=None):
        self.name=nm
        self.salary=sal
    def getName(self):
        return self.name
    def getSalary(self):
        return self.salary

class SalesOfficer(Employee):
    def _init_(self,nm=None,sal=None,inc=None):
        super()._init_(nm,sal)
        self.incnt=inc
        def getSalary(self):
            return self.salary+self.incnt

【问题讨论】:

  • _init_ 不正确。它应该有两个下划线:__init__.
  • @Devesh 我认为通过添加class Employee 行,您可能已经掩盖了错误。我怀疑它的位置可能还有其他东西。
  • 我刚刚纠正了缩进,class Employee 行与三引号在同一行,导致该行不显示,我只是将该行放在下一行!然后它出现了!现在你最后一次编辑覆盖了@NickT :(
  • @DeveshKumarSingh derp,修订查看器根本没有渲染它。对不起stackoverflow.com/revisions/55962624/1

标签: python


【解决方案1】:

构造函数命名为__init__(init 两边有两个下划线)而不是_init_(只有一个下划线),只需更改它,您的代码就可以工作

class Employee:

    #Fixed this
    def __init__(self, nm=None, sal=None):
            self.name=nm
            self.salary=sal

    def getName(self):
        return self.name

    def getSalary(self):
        return self.salary

class SalesOfficer(Employee):

    # Fixed this
    def __init__(self,nm=None,sal=None,inc=None):
        super()._init_(nm,sal)
        self.incnt=inc

    def getSalary(self):
        return self.salary+self.incnt


e1=Employee("Rajesh",9000)
print(e1.getName())
print(e1.getSalary())

输出将是

Rajesh
9000

这里要注意一点,然后当我尝试运行 OP 的原始代码时,我得到了TypeError: Employee() takes no arguments 而不是 OP 得到的object.__new__() takes no parameters,但在我看来,这两个错误都指向同一个方向,它说因为没有定义__init__,你不能在构造函数中设置任何属性!

【讨论】:

  • 那可能是什么原因造成的呢?我解决了这个问题并且代码有效!
  • 在我的情况下@wim 我也得到TypeError: Employee() takes no arguments 而不是OP 得到的object.__new__() takes no parameters!我认为这两个错误都指向同一个方向,因为没有定义__init__,所以你不能在构造函数中设置任何属性!
猜你喜欢
  • 2015-01-15
  • 2016-04-03
  • 2013-06-09
  • 1970-01-01
  • 2011-07-06
  • 2013-11-18
  • 1970-01-01
  • 1970-01-01
  • 2011-01-26
相关资源
最近更新 更多