在类定义中,super()等价于super(Child, self)。实际上解释器使用的是__class__变量,每个函数中都能访问这个变量,它指向这个函数对应的类。注意,这个特殊语法只能在Python3中使用,不能在Python2中使用。这个新的功能是2007年引入到Python 3.0版本中的,详见PEP-3135提案。3.__init__/__new__以及实
super().xx(),就是继承父类的 xx() 方法 比如:super(ChildClass, self).__init__()首先找到ChildClass的父类FatherClass,然后将ChildClass类的对象转化为父类的对象,让这个 被转化的对象 调用自己的(就是FatherClass)的__init__()函数 代码: classFatherClass():def__init__(self):self.fathername="fa...
super(Child,self).__init__('Tom') #要将子类Child和self传递进去 #c = Child("init Child") d = Parent('tom') c = Child() 输出: ('create an instance of:', 'Parent') ('name attribute is:', 'tom') ('create an instance of:', 'Child') ('name attribute is:', 'Tom') 3、s...
init(self)这种写法虽然也能实现相同的效果,但在Python社区中并不推荐使用。这种方式需要在子类中显式地写出父类的类名和初始化方法名,这会增加代码的复杂性和出错的可能性。另外,如果父类发生改变(例如父类被重命名或删除),这种方式可能会导致代码出错。总结来说,super().init()和xxxClass.init(self)都可以用...
classinitial(object):def__init__(self):print('This print is from initial object')self.param=3deffunc(self):return1classnew(initial):def__init__(self):print('This print is from new object')print(self.func())super(new,self).__init__()print(self.param)self.param=4if__name__=='_...
Base.__init__(self)classchildB(Base):def__init__(self):print'creat B', super(childB, self).__init__() base=Base() a=childA() b=childB()#输出:Base create creat A Base create creat B Base create 使用super()继承时不用显式引用基类。
classParentClass1:def__init__(self):super().__init__()# 父类1的初始化方法的其他代码classParentClass2:def__init__(self):super().__init__()# 父类2的初始化方法的其他代码classChildClass(ParentClass1,ParentClass2):def__init__(self):super(ChildClass,self).__init__()# 子类的初始化...
class Parent(object): def __init__(self, name): = name print("create an instance of:", self.__class__.__name__) print("name attribute is:", )#子类继承父类 class Child(Parent): def __init__(self): print("call __init__ from Child class") super(Child,self).__init__("小...
我们在使用python中的类继承时,子类继承父类后,在重载父类的方法后,在方法中如果要执行父类对应的方法,一般有两种方式:super和Base(表示父类名)。 使用例子 先看下面一段代码: # -*- coding: utf-8 -*- class Base: def __init__(self):
class Complex: def __init__(self, realpart, imagpart): self.r = realpart self.i = imagpart x = Complex(3.0, -4.5) print(x.r, x.i) # 输出结果:3.0 -4.5 self代表类的实例,而非类 类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称, 按照惯例它的名称是 se...