Python 三大特性
一、三大特性:
封装、继承、多态
二、构造方法
1.封装
__init__方法,用来初始化,当创建对象时自动调用
class Person(): def __init__(self,name,age,gender): self.name=name self.age=age self.gender=gender def show(self): print("%s--%s--%s" % (self.name, self.age, self.gender)) gyc=Person('gyc','25','male') gyc.show() #gyc--25--male
2.继承:
2.1子类可以继承并调用父类方法,父类不能调用子类方法,当子类没有方法时,逐级调用子类》父类》爷类
1 class Person(object): 2 def foo(self): 3 print('wo sshi fu lei') 4 class Son(Person): 5 def foo_new(self): 6 print('wo shi zi lei') 7 p=Person() 8 p.foo() 9 print('----') 10 s=Son() 11 s.foo_new() 12 s.foo() 13 #wo sshi fu lei 14 #---- 15 #wo shi zi lei 16 #wo sshi fu lei
2.2 子类可以重写并覆盖父类的方法,调用时优先选择子类方法
1 class Person(object): 2 def foo(self): 3 print('wo shi fu lei') 4 class Son(Person): 5 def foo_new(self): 6 print('wo shi zi lei') 7 def foo(self): 8 print('wo shi xin fu lei') 9 p=Person() 10 p.foo() 11 print('----') 12 s=Son() 13 s.foo_new() 14 s.foo() 15 #wo shi fu lei 16 #---- 17 #wo shi zi lei 18 #wo shi xin fu lei
self永远指向调用方法的调用者对象
2.3 子类显式的调用父类方法
2.3.1super(子类名,self).父类方法
1 class Son(Person): 2 def foo_new(self): 3 print('wo shi zi lei') 4 def foo(self): 5 super(Son,self).foo() 6 print('wo shi xin fu lei') 7 s=Son() 8 s.foo_new() 9 s.foo() 10 #wo shi zi lei 11 #wo shi fu lei 12 #wo shi xin fu lei
2.3.2父类名.父类方法(self)
Person.foo(self)
2.4 支持多继承
2.4.1调用父类方法1
1 class F(object): 2 def foo(self): 3 print('F.foo') 4 class F1(object): 5 def foo(self): 6 print('F1.foo') 7 class S(F1,F): 8 pass 9 s=S() 10 s.foo() 11 #F1.foo
当多继承时,按照继承顺序先后寻找执行,默认如果第一个父类没有自动在父类查看是否存在父类的父类,如果其中存在方法则执行,
第一个父类的线走完没有才走第二个父类。
当多继承中两个父类存在相同的父类,则不会从第一个父类那条线走下去找基类,而是先去找第二个父类
总结:左侧优先,一条道走到黑,同一个根时根最后执行
2.4.1调用父类方法2
1 class Father1(object): 2 def foo(self): 3 print('Father1.foo') 4 class Father2(object): 5 def foo(self): 6 print('Father2.foo') 7 def foo_new(self): 8 print('Father2.foo_new') 9 self.foo() 10 class Son(Father1,Father2): 11 pass 12 s=Son() 13 s.foo_new() 14 #Father2.foo_new 15 #Father1.foo
总结:每次调用方法都是优先左侧开始
3.多态
浙公网安备 33010602011771号