在继承时我需要初始化父类吗?

yay*_*ayu 2 python super

如果我从一个类继承并且没有更改方法中的任何内容,是否需要使用super来从父类初始化该方法?

class A:

   def __init__(self):
       self.html = requests.get("example.com").text


class B(A):

    def __init__(self):
        # is this needed?
        super(B, self).__init__()

    def new_method(self):
        print self.html
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

因为您__init__在类中创建了一个方法B,所以它会覆盖类中的方法A.如果你想要它被执行,你将不得不使用super(),是的.

但是,如果你没有做什么其他B.__init__,你可能也只是忽略它:

class A:
   def __init__(self):
       self.html = requests.get("example.com").text

class B(A):
    def new_method(self):
        print self.html
Run Code Online (Sandbox Code Playgroud)

如果你想做的任何事情,除了什么A.__init__()呢,那么有必要创建一个B.__init__()方法,并从方法,调用父__init__.