当需要传递时,Python要求两个参数

时间:2014-08-12 18:26:45

标签: python object inheritance

我是python的新手,正在研究这段代码:

class Shape:
    def __init__(self, shape):
        self.shape = shape

    def shapeName(self):
        print(self.shape)

class Rectangle(Shape):                         # Rectangle class inherits Shape

    count = 0                                   # static variable

    def __init__(self, name):
        Shape.__init__(self.name)
        print('In Rectangle')
        Rectangle.count = Rectangle.count + 1


rec1 = Rectangle('Rectangle')
rec2 = Rectangle('Rectangle')

rec1.shapeName()
rec2.shapeName()

print( Rectangle.count )

我收到以下错误:

C:\Python32\python.exe C:/Users/ashutosh/PycharmProjects/Test/InheritanceTest.py

Traceback (most recent call last):

File "C:/Users/ashutosh/PycharmProjects/Test/InheritanceTest.py", line 17, in <module>

rec = Rectangle('Rectangle')

File "C:/Users/ashutosh/PycharmProjects/Test/InheritanceTest.py", line 13, in __init__

Shape.__init__(name)

TypeError: __init__() takes exactly 2 arguments (1 given)

Process finished with exit code 1

构造函数的第一个参数是当前对象,第二个是形状的名称。那么为什么说我必须传递2个参数?

2 个答案:

答案 0 :(得分:4)

您必须明确将self传递给Shape.__init__

所以你的矩形类应该是这样的:

class Rectangle(Shape):                         # Rectangle class inherits Shape

    count = 0

    def __init__(self, name):
        Shape.__init__(self, name)
        print('In Rectangle')

答案 1 :(得分:4)

Shape是一个类,而不是一个对象,所以当你调用Shape.__init__时,没有自变量。换句话说,没有Shape的实例可以调用init。您想要的实例是您拥有的Shape的子类实例,即selfRectangle)。你可以简单地传递自我,就像这样:

Shape.__init__(self, name)

或使用super关键字:

super(Rectangle, self).__init__(name)

super关键字允许您隐式引用您的超类,而不使用该名称。

在Python 3.0中,您甚至可以简单地编写super().__init__(name),甚至没有子引用。