Python Class super().__init__() 作用
在 python3 中为super()._init_()在 python2 中 为super(classname, self)._init_()先定义一个父类 A,里面的 init 构造函数class A:def __init__ (self, w):self.w = wdef aa(self, a):a = self.wprint(a)class B(A):def __init__ (self,
在 python3 中为
super().__init__()
在 python2 中 为
super(classname, self).__init__()
先定义一个父类 A,里面的 __init__ 构造函数,由 B 类继承,但是没有使用 super().__init__() ,但是在其中的方法部分写了 A 的属性 self.w,执行 B 类实例化并调用 bb function,语法报错
class A:
def __init__ (self, w):
self.w = w
def aa(self, a):
a = self.w
print(a)
class B(A):
def __init__ (self, w):
pass
def bb(self, b):
b = self.w
print(b)
b = B(9)
b.bb(3)
这次加了 super().__init__(),但还是报错
class B(A):
def __init__ (self, w):
super().__init__()
def bb(self, b):
b = self.w
print(b)
b = B(9)
b.bb(3)
再加上参数,程序运行正常
class B(A):
def __init__ (self, w):
super().__init__(3)
def bb(self, b):
b = self.w
print(b)
b = B(9)
b.bb(3)
所以 super().__init__() 主要作用是让子类继承父类的类属性,因为一般类属性都是在父类的 __init__ 函数里构造的,在 pytorch 里面 nn.Module 类都是用 super().__init__() 继承的,因为 class nn.Module 里面 def __init__(self) 没有参数,所以不用传递
传递参数的时候如果使用 super 类不用写 self,如 super().__init__(3)
老式写法需要写 self,如 A.__init__(self, 3)

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)