相关疑难解决方法(0)

使用__init __()方法理解Python super()

我正在努力了解它的用法super().从它的外观来看,可以创建两个子类,就好了.

我很想知道以下2个孩子班级之间的实际差异.

class Base(object):
    def __init__(self):
        print "Base created"

class ChildA(Base):
    def __init__(self):
        Base.__init__(self)

class ChildB(Base):
    def __init__(self):
        super(ChildB, self).__init__()

ChildA() 
ChildB()
Run Code Online (Sandbox Code Playgroud)

python oop inheritance class super

2366
推荐指数
7
解决办法
158万
查看次数

"超级"在Python中做了什么?

有什么区别:

class Child(SomeBaseClass):
    def __init__(self):
        super(Child, self).__init__()
Run Code Online (Sandbox Code Playgroud)

和:

class Child(SomeBaseClass):
    def __init__(self):
        SomeBaseClass.__init__(self)
Run Code Online (Sandbox Code Playgroud)

我已经看到super在只有单继承的类中使用了很多.我可以看到为什么你在多重继承中使用它,但不清楚在这种情况下使用它的优点是什么.

python oop inheritance super

522
推荐指数
7
解决办法
21万
查看次数

[python]:被super()搞糊涂了

可能重复:
了解Python super()

类的B子类A,所以在B中__init__我们应该__init__像这样调用A :

class B(A):
    def __init__(self):
        A.__init__(self)  
Run Code Online (Sandbox Code Playgroud)

但是super(),我看到这样的事情:

class B(A):
    def __init__(self):
        super(B, self).__init__()  #or super().__init__()
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  1. 为什么不super(B, self).__init__(self)呢?仅仅因为返回代理对象是绑定的?

  2. 如果我在super中省略第二个参数并且返回代理对象是未绑定的,那么我应该写super(B).__init__(self)吗?

python super

4
推荐指数
1
解决办法
1246
查看次数

python,继承,super()方法

我是python的新手,我有下面的代码,我无法开始工作: - 这是继承,我有一个圆基类,我在一个circle类中继承它(这里只是单继承).

我理解这个问题是在类中的ToString()函数内circle,特别是行,text = super(Point, self).ToString() +.. 它至少需要一个参数,但我得到了这个:

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

我知道super没有ToString属性,但Point课程确实 -

我的代码:

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 …
Run Code Online (Sandbox Code Playgroud)

python inheritance super

3
推荐指数
1
解决办法
4612
查看次数

标签 统计

python ×4

super ×4

inheritance ×3

oop ×2

class ×1