标签:python2 fun name not col odi har style html
super() 函数是用于调用父类(超类)的一个方法。
super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。
MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。
Python3.x 和 Python2.x 的一个区别是: Python 3 可以使用直接使用 super().xxx 代替 super(Class, self).xxx :
Python3.x 实例:
class A:
pass
class B(A):
def add(self, x):
super().add(x)
Python2.x 实例:
class A(object): # Python2.x 记得继承 object
pass
class B(A):
def add(self, x):
super(B, self).add(x)
#!/usr/bin/python # -*- coding: UTF-8 -*- class FooParent(object): def __init__(self): self.parent = ‘I\‘m the parent.‘ print (‘Parent‘) def bar(self,message): print ("%s from Parent" % message) class FooChild(FooParent): def __init__(self): # super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类B的对象 FooChild 转换为类 FooParent 的对象 super(FooChild,self).__init__() print (‘Child‘) def bar(self,message): super(FooChild, self).bar(message) print (‘Child bar fuction‘) print (self.parent) if __name__ == ‘__main__‘: fooChild = FooChild() fooChild.bar(‘HelloWorld‘)
super()
的好处就是可以避免直接使用父类的名字.但是它主要用于多重继承,这里面有很多好玩的东西.如果还不了解的话可以看看官方文档Python不会自动调用父类的constructor,你得亲自专门调用它。
两种方法:
# coding=utf-8 class Person(object): def __init__(self, name="jim"): self.name = name self.flag = False print "Person",self.name def call(self): print self.flag,"name:",self.name self.flag = not self.flag class Programmer(Person): def __init__(self): Person.__init__(self,"Dotjar") #第一种方法 print "Programmer" def set_name(self,name): self.name=name coder = Programmer() coder.call() coder.set_name("dotjar") coder.call()
# coding=utf-8 class Person(object): def __init__(self, flag=False, name="jim"): self.name = name self.flag = flag print "Person",self.name def call(self): print self.flag,"name:",self.name self.flag = not self.flag class Programmer(Person): def __init__(self, flag = True, name="Dotjar",age = 19): self.age = 19 super(Programmer,self).__init__(flag,name) # 第二种方法 print "Programmer‘s age:",self.age def set_name(self,name): self.name=name
https://code.i-harness.com/zh-CN/q/5ad4a
标签:python2 fun name not col odi har style html
原文地址:https://www.cnblogs.com/ranjiewen/p/9218851.html