Python类继承__init__

时间:2017-04-02 00:23:59

标签: python class

所以,这就是问题..

如果你这样做:

class x(object):
  def __init__(self):
    pass

为什么要在子类中显式调用 init 来访问父类属性? (无论如何,类y都有类x属性。)

class y(x):
  def __init__(self):
    x.__init__(self)

干杯。

编辑:

我读了这篇文章https://linuxmeerkat.wordpress.com/2015/04/28/why-you-should-use-super-in-python/,它说"在现实生活中,我们倾向于为每个父类运行初始化程序。这只是,因为程序设计往往是。在我们的简单示例中,解决此问题的方法是显式调用A:"的初始值设定项。有人可以解释一下吗?

3 个答案:

答案 0 :(得分:0)

因为子类继承自父类,当然,这意味着它永远:方法,属性和构造函数。 因此,您只需使用已在父类中编写的代码,而不是重写所有__init__代码。 希望对你有意义。

答案 1 :(得分:0)

事实是,在python中,类和实例属性之间有明显的区别:

  • 在类体中声明的属性,在任何方法之外,都是类属性,它们对于该类的每个对象都是相同的,并且是子类继承的属性。请注意,执行instance_obj.class_att = something并不会更改类属性的值,而只是创建一个实例属性并隐藏该对象的共享类属性。

  • 实例属性是使用语法instance_obj.att = something声明的属性,它们不在实例之间共享,与您在非静态属性中最相似其他编程语言通常在 init 方法中创建。self只是一个约定,表示实例对象自动传递给方法。

以下是一个例子:

class MyClass:
    c = 1                    #class attribute, the subclasses will inherit this
    def __init__(self):
        self.i = 1           #instance attribute

MyClass.c     #access attribute c of class MyClass
MyClass.i     #error! MyClass has no attribute i
x = MyClass() #calling __init__ creates instance attribute i for obj x
x.i           #access instance attribute i of object x
x.c           #access class attribute c of class MyClass
x.c = 2       #hide MyClass.c and create instance attribute c for obj x
x.c           #access instance attribute c of obj x

总而言之,做:

class y(x):
    def __init__(self):
        x.__init__(self)

很有用,因为如果基类就是这样的

class x:
    def __init__(self):
        self.i=1

你将无法从y的任何实例访问属性i,因为他们没有它。

答案 2 :(得分:0)

不应显式调用 init 函数,而应使用super()方法。

在python 3.0+中,您可以使用:

class y(x):
    def __init__(self):
        super().__init__()

在python 2.7或更低版​​本中,使用:

class y(x):
    def __init__(self):
        super(self.__class__, self).__init__()

super()可以避免显式引用基类。