TypeError: this constructor takes no arguments

版权声明:本文为小盒子原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35393693/article/details/82109774

在使用python编写面向对象的程序时,若书写不小心很可能遇到TypeError: this constructor takes no arguments这个错误。

class Plane:
    '''feijiziwojeishao

    zheliyouhenduofenji'''
    pCount=0
    def _init_(self,name,category):
        self.name=name
        self.category=category
        Plane.pCount+=1
    def _del_(self):
        class_name=self._class_._name_
        print class_name
    def displayPlane(self):
        print 'Name:',self.name,'Category:',self.category
    
p1=Plane('平平安安','播音666')
p2=p1
p3=p1
print id(p1),id(p2),id(p3)

运行报错如下:

出错原因是,在python中构造函数书写格式是__init__,而不是_init_,即在init两侧都是双下划线,不是单下划线。

因此原程序应改为:

class Plane:
    '''feijiziwojeishao

    zheliyouhenduofenji'''
    pCount=0
    def __init__(self,name,category):
        self.name=name
        self.category=category
        Plane.pCount+=1
    def _del_(self):
        class_name=self._class_._name_
        print class_name
    def displayPlane(self):
        print 'Name:',self.name,'Category:',self.category
    
p1=Plane('平平安安','播音666')
p2=p1
p3=p1
print id(p1),id(p2),id(p3)

此时在运行就正常了:

猜你喜欢

转载自blog.csdn.net/qq_35393693/article/details/82109774