Python 3个继承等效语句
Python 3 inheritance equivalent statements
从此处的文档中,它声称 super().method(arg) 与以下内容执行相同的操作:super(C, self).method(arg).
https://docs.python.org/3/library/functions.html#super
class shape(object):
def __init__(self, type):
self.shapeType = type
class coloredShape1(shape):
def __init__(self, type, color):
super().__init__(type)
self.shapeColor = color
class coloredShape2(shape):
def __init__(self, type, color):
super(shape, self).__init__(type)
self.shapeColor = color
circle = shape("circle")
blueRectangle = coloredShape1("rectangle", "blue")
redSquare = coloredShape2("square", "blue")
创建 blueRectangle 没有问题,但是,redSquare 行抛出以下预期:
Traceback (most recent call last):
File "test.py", line 17, in <module>
redSquare = coloredShape2("square", "blue")
File "test.py", line 12, in __init__
super(shape, self).__init__(type)
TypeError: object.__init__() takes no parameters
我不明白两者之间的区别。有人可以解释我做错了什么吗?
您将错误的 class 传递给了 super()
,因此您调用了 object.__init__
,而不是 shape.__init__
。
class coloredShape2(shape):
def __init__(self, type, color):
super(coloredShape2, self).__init__(type)
self.shapeColor = color
从此处的文档中,它声称 super().method(arg) 与以下内容执行相同的操作:super(C, self).method(arg).
https://docs.python.org/3/library/functions.html#super
class shape(object):
def __init__(self, type):
self.shapeType = type
class coloredShape1(shape):
def __init__(self, type, color):
super().__init__(type)
self.shapeColor = color
class coloredShape2(shape):
def __init__(self, type, color):
super(shape, self).__init__(type)
self.shapeColor = color
circle = shape("circle")
blueRectangle = coloredShape1("rectangle", "blue")
redSquare = coloredShape2("square", "blue")
创建 blueRectangle 没有问题,但是,redSquare 行抛出以下预期:
Traceback (most recent call last):
File "test.py", line 17, in <module>
redSquare = coloredShape2("square", "blue")
File "test.py", line 12, in __init__
super(shape, self).__init__(type)
TypeError: object.__init__() takes no parameters
我不明白两者之间的区别。有人可以解释我做错了什么吗?
您将错误的 class 传递给了 super()
,因此您调用了 object.__init__
,而不是 shape.__init__
。
class coloredShape2(shape):
def __init__(self, type, color):
super(coloredShape2, self).__init__(type)
self.shapeColor = color