【问题标题】:Python class--Super variablePython 类--超级变量
【发布时间】:2015-02-03 12:24:32
【问题描述】:

由于某种原因,下面的代码给了我一个错误,谁能告诉我会是什么问题..

基本上,我创建了 2 个类 Point 和 Circle..The circle 试图继承 Point 类。

Code:


class Point():

    x = 0.0
    y = 0.0

    def __init__(self, x, y):
        self.x = x
        self.y = y
        print("Point constructor")

    def ToString(self):
        return "{X:" + str(self.x) + ",Y:" + str(self.y) + "}"

class Circle(Point):
    radius = 0.0

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

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


if __name__=='__main__':
        newpoint = Point(10,20)
        newcircle = Circle(10,20,0)

错误:

C:\Python27>python Point.py
Point constructor
Traceback (most recent call last):
  File "Point.py", line 29, in <module>
    newcircle = Circle(10,20,0)
  File "Point.py", line 18, in __init__
    super().__init__(x,y)
TypeError: super() takes at least 1 argument (0 given)

【问题讨论】:

  • 您是否对源代码进行了一些编辑?你的init 电话原来是这样的吗?
  • ToString,哦!我的(蟒蛇式)眼睛在流血

标签: python


【解决方案1】:

看起来您可能已经修复了原始错误,该错误是由 super().__init__(x,y) 引起的,如错误消息所示,尽管您的修复略有错误,但您应该使用 Circle 类中的 super(Point, self) 而不是 @ 987654325@.

请注意,在CircleToString() 方法内部,还有另一个地方错误地调用了super()

        return super().ToString() + \
               ",{RADIUS=" + str(self.radius) + "}"

这是 Python 3 上的有效代码,但在 Python 2 上 super() 需要参数,将其重写为:

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

我还建议去掉续行,请参阅Maximum Line Length section of PEP 8 了解修复此问题的推荐方法。

【讨论】:

  • 错误消息明确指出错误不是来自该行。
  • @MarkRansom - 没错!谢谢。
  • 你应该建议 ToString() 不是(根本)正确的想法,这就是 __str__ 的用途。
【解决方案2】:

super(..) 只接受新式类。要修复它,请从 object 扩展 Point 类。像这样:

class Point(object):

另外,使用 super(..) 的正确方法是:

super(Circle,self).__init__(x,y)

【讨论】:

    【解决方案3】:
    class Point(object):
    
    x = 0.0
    y = 0.0
    
    def __init__(self, x, y):
        self.x = x
        self.y = y
        print("Point constructor")
    
    def ToString(self):
        return "{X:" + str(self.x) + ",Y:" + str(self.y) + "}"
    
    class Circle(Point,object):
    radius = 0.0
    
    def __init__(self, x, y, radius):
        super(Circle,self).__init__(x,y)
        self.radius = radius
        print("Circle constructor")
    
    def ToString(self):
        return super(Circle, self).ToString() + \
               ",{RADIUS=" + str(self.radius) + "}"
    
    
    if __name__=='__main__':     
        newpoint = Point(10,20)    
        newcircle = Circle(10,20,0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-10
      • 1970-01-01
      • 2018-10-01
      • 1970-01-01
      • 2014-08-20
      • 1970-01-01
      • 2021-02-24
      相关资源
      最近更新 更多