day 16 初始面向对象
---恢复内容开始---
面向对象
什么是面向对象?
面向过程:
一切一失误的发展流程为中心.
面向对象:
一切以对象为中心,一切皆对象,具体的某一个事物就是对象.
造一个对象:
class Duixiang: #类名首字母大写,严格遵守驼峰命名规范 def __init__self: print("我是init") Duixiang() #创建对象
封装
注意:封装有对属性的封装,对方法的封装(静态封装,动态封装)
用面向对象造车:
class Car: #静态属性 def __init__(self,yanse,chepai,pailiang): self.yanse = yanse self.chepai = chepai self.pailiang = pailiang #动态方法 def pao(self): print("%s的我的车能跑" %self.yanse) def jump(self): print("我的车能跳") c1 = Car("黑色",666,"1.6T") c2 = Car("绿色",888,"2.0T") c1.pao() #黑色的我的车能跑 c2.pao() #绿色的我的车能跑 print(c1.__dict__) #{'yanse': '黑色', 'chepai': 666, 'pailiang': '1.6T'} print(c2.__dict__) #{'yanse': '绿色', 'chepai': 888, 'pailiang': '2.0T'}
用面向对象打电话:
class Phone: def __init__(self,dianchi,number,price): self.dianchi = dianchi self.number = number self.price = price def call(self,ren): print("使用我的%s的手机给%s打电话" % (self.dianchi,ren)) def play(self,iphone): print("%s手机还能玩游戏" % iphone) apple = Phone("5W毫安",110, 7000)
apple.call("嫂子") #使用我的5W毫安的手机给嫂子打电话 apple.play("苹果") #苹果手机还能玩游戏
用面想对象的思维来模仿用户登录
class User: def __init__(self,usernam): self.username = usernam self.upwd = "123" def login(self): uname = input("请输入用户名:") upwd = input("请输入密码:") if uname == self.username and upwd == self.upwd: print("登录成功!") else: print("登录失败") yanpei = User("nana") yanpei.login()
继承
注意:子类可以继承父类的东西,父类不能调用子类的功能,类中的查询顺序,先找自己然后再找父类
单继承
class Foo: def getmonery(self): print("拿钱") class Bar(Foo): def getmonery(self): #先找自己然后再找父类 print("取钱") a = Bar() a.getmonery() #取钱
多继承
class Foo1: def getmoner(self): print("拿钱") class Foo2: def getmoney(self): print("取钱") class Bar(Foo1,Foo2): #继承顺序是从往右 pass c = Bar() c.getmoner() #拿钱
多态
注意:鸭子模型:同一个对象多种形态. 会嘎嘎叫的就行,不管是什么动物
class Animal: def chi(self): print("动物会吃") class Laohu(Animal): print("老虎吃肉") class Daxiang(Animal): print("大象吃香蕉") class Houzi(Animal): print("猴子吃的五花八门,用手拿着吃") #饲养员 def weidngwu(dongwu): dongwu.chi() l = Laohu() d = Daxiang() h = Houzi() weidngwu(l) weidngwu(d) weidngwu(h)