Skip to main content
 首页 » 编程设计

Python 在需要传递一个参数时要求两个参数

2025年05月04日12sxdcgaq8080

我是 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 个参数?

请您参考如下方法:

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

Shape.__init__(self, name) 

或者使用 super 关键字:

super(Rectangle, self).__init__(name) 

super 关键字允许您隐式引用您的父类(super class),而无需使用名称。

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