面向对象继承
一、回顾
class ATM: __info = {123456:{"name":"md","money":1},345678:{"name":"dennis","money":2}} # 输入卡号验证是否有一个私有方法,保证账号的正确性 def __check_idcard(self): self.id_card = eval(input("请输入您的卡号:")) info = self.__info.get(self.id_card) if not info: return "您重新输入的卡号" return info # 余额查询操作 @property def money(self): info = self.__check_idcard() if isinstance(info,dict): return info["money"] # 存款或者取款的操作 @money.setter def money(self,money): info = self.__check_idcard() if not isinstance(info,dict): print("请输入正确的卡号") return elif 0 < money < 100: print("请输入正确的金额") return else: # {123456: {"name": "md", "money": 1}, 345678: {"name": "dennis", "money": 2}} if money < 0: if abs(money) > self.__info[self.id_card]["money"]: print("余额不足,请先存钱") return self.__info[self.id_card]["money"] += money print("操作成功") return if __name__ == "__main__": while True: mney = eval(input("money")) if mney == 0: print("本次操作结束") break ss = ATM() ss.money = mney print(ss.money)
二、继承
2.1 定义及益处
继承好处: 代码重用 如果定义了一个class,继承了某个现有的class,新的class称为子类(subclass),而被继承的类称为基类、父类或者超类(Base class,Super class)
2.2 单一继承
格式:
class Obj(object): pass
# 类定义 class People: # 定义基本属性 name = "" age = 0 __weight = 0 # 构造方法 def __init__(self,n,a,w): self.name = n self.age = a self.__weight = w def speak(self): print("%s 说:我目前年龄 %d 正当学PY" %(self.name,self.age)) # 单继承 class Stu(People): grade = "" def __init__(self,n,a,w,g): People.__init__(self,n,a,w) self.grade = g # 重写父亲的方法 def speak(self): print("%s说:我目前年龄%d正当学PY,我目前是%s年级" % (self.name, self.age,self.grade)) p1 = Stu("lyy",15,120,"2") p1.speak() p2 = People("md",45,"js") p2.speak()
2.3 多继承
格式
class MultiClsName(Base1,Base2,Base3....): pass
class Dog: def fun(self): print("Dog.fun") class Wolf(Dog): def fun(self): super(Wolf,self).fun() print("Wolf.fun") class ZA(Dog): def fun(self): super(ZA,self).fun() print("ZA.fun") class Army(Wolf,ZA): def fun(self): super(Army,self).fun() print("Army.fun") # print(Army.mro()) army = Army() army.fun()
多继承中的C3算法:
上述例子中查找顺序是:Army=>Wolf=>ZA=>Dog
输出顺序是:Dog=>ZA=>Wolf=>Army
图中查找顺序:G=>B=>E=>C=>A=>F(首先先看G,除了之后,上面的两个箭头就消失了,然后再有左右原则,对B进行去箭头,然后左右原则取E,然后在返回来选C,依次进行)
输出顺序:E=>B=>G