简体   繁体   English

python,继承,super()方法

[英]python, inheritance, super() method

I'm new to python, I have the code below which I just can't get to work:- This is inheritance, I have a circle base class and I inherit this within a circle class (just single inheritance here). 我是python的新手,下面有一些我无法使用的代码:-这是继承,我有一个圈子基类,我在一个circle类中继承了它(这里只是单个继承)。

I understand the issue is within the ToString() function within the circle class, specifically the line, text = super(Point, self).ToString() +.. which requires at least a single argument, yet I get this: 我知道问题出在circle类的ToString()函数内,特别是线text = super(Point, self).ToString() +..这至少需要一个参数,但是我得到了:

AttributeError: 'super' object has no attribute 'ToString'

I know super has no ToString attribute, but the Point class does - 我知道super没有ToString属性,但是Point类确实有-

My code: 我的代码:

class Point(object):
    x = 0.0
    y = 0.0

    # point class constructor
    def __init__(self, x, y):
        self.x = x
        self.y = y
        print("point constructor")

    def ToString(self):
        text = "{x:" + str(self.x) + ", y:" + str(self.y) + "}\n"
        return text

class Circle(Point):
    radius = 0.0

    # circle class constructor
    def __init__(self, x, y, radius):
        super(Point, self)              #super().__init__(x,y)
        self.radius = radius
        print("circle constructor")

    def ToString(self):
        text = super(Point, self).ToString() + "{radius = " + str(self.radius) + "}\n"
        return text


shapeOne = Point(10,10)
print( shapeOne.ToString() ) # this works fine

shapeTwo = Circle(4, 6, 12)
print( shapeTwo.ToString() ) # does not work

You need to pass in the Circle class instead: 您需要传递Circle类:

text = super(Circle, self).ToString() + "{radius = " + str(self.radius) + "}\n"

super() will look through the base classes of the first argument to find the next ToString() method, and Point doesn't have a parent with that method. super()将遍历第一个参数的基类以找到下一个ToString()方法,并且Point没有该方法的父级。

With that change, the output is: 进行此更改后,输出为:

>>> print( shapeTwo.ToString() )
{x:0.0, y:0.0}
{radius = 12}

Note that you make the same mistake in your __init__ ; 注意,您在__init__犯了同样的错误; you are not calling the inherited __init__ at all. 您根本没有调用继承的__init__ This works: 这有效:

def __init__(self, x, y, radius):
    super(Circle, self).__init__(x ,y)
    self.radius = radius
    print("circle constructor")

and then the output becomes: 然后输出变为:

>>> shapeTwo = Circle(4, 6, 12)
point constructor
circle constructor
>>> print( shapeTwo.ToString() )
{x:4, y:6}
{radius = 12}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM