python基础学习2020.6.25-面向对象

1.类的创建

class people:
 
    def __init__(self):#构造函数
        pass
 
Derrick=people()#类的实例

2.封装

class people:
 
    def __init__(self,name,age):
        self.name=name
        self.age=age
 
sfencs=people("Derrick",19)
print("%s is %d"%(Derrick.name,sfencs.age))

3.继承

class father:
    def __init__(self):
        self.a = 1
        self.b = 2
 
    def me(self):
        print("i am father")
        print(self)#<__main__.son object at 0x000001F7DFA11128>
 
class son(father):
 
    def __init__(self):
        super().__init__()
        super(son,self).me()#执行父类的me方法,但self是people
 
    def me(self):
        print("i am son")
 
people=son()
print(people.a)#1
people.me()#i am son

子类可以对父类的方法进行重写,子类调用父类的方法使用super(子类名,self),self永远是执行该方法的调用者

python支持多继承

class father1:
    def __init__(self):
        self.a = 1
        self.b = 2
 
    def me(self):
        print("i am father1")
 
class father2:
    def __init__(self):
        self.c = 3
        self.d = 4
 
    def me(self):
        print("i am father2")
 
class son(father1,father2):
 
    def __init__(self):
        father1.__init__(self)
        father2.__init__(self)
        super(son,self).me()#i am father1
 
    def me(self):
        print("i am son")
 
people=son()
print(people.c)#3
people.me()#i am son

多继承中子类调用父类方法的寻找方法是按照父类声明的顺序从左到右,从下到上查找,一直查找到最高级的父类,但是如果不同的父类继承于同一个父类,

那么这个相当于根的父类为最后再去查找

4.多态

class Duck(object):                                  # 鸭子类
    def fly(self):
        print("鸭子沿着地面飞起来了")

class Swan(object):                                  # 天鹅类
    def fly(self):
        print("天鹅在空中翱翔")

class Plane(object):                                 # 飞机类
    def fly(self):
        print("飞机隆隆地起飞了")

def fly(obj):                                        # 实现飞的功能函数
    obj.fly()

duck = Duck()
fly(duck)

swan = Swan()
fly(swan)

plane = Plane()
fly(plane)

===运行结果:===================================================================================
鸭子沿着地面飞起来了
天鹅在空中翱翔
飞机隆隆地起飞了

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值