继承

class RichMan:
    #富一代自己账户
    def __init__(self,money,company):
        self.money = money
        self.company = company

    def earnMoney(self,number):
        self.money +=number #挣钱

    def spendMoney(self,numer):
        self.money -=numer

    def showMoney(self): #炫富
        print('Rich man has:' + str(self.money))

class RichChild(RichMan): #继承RichMan
    #富二代长大了需要自己账户def __init__(self,money,company):
    def __init__(self,money,company):#当子类定义自己的init方法,务必先显示调用父类的init方法,否则父类会初始化失败
        super().__init__(money,company)#显示调用父类init方法,确保父类初始化成功
        self.ownMoney = 0 #富二代自己的资产

    def earnMoney(self,number):#子类定义了跟父类一样的方法会覆盖父类
        self.ownMoney += number

    def spendMoney(self,number):  #花的钱
        if self.ownMoney == 0:#富二代自己没挣钱
            self.money -= number#花老爸的 啃老
        else:
            if  self.ownMoney >=number:
                self.ownMoney -=number
            else:
                self.money -= (number - self.ownMoney)#先减去自己的然后减去老爸的
                self.ownMoney =0

    def showMoney(self):
        if self.ownMoney >0:
            print('我有'+ str(self.ownMoney))
        else:
            print('我有我爸爸的钱'+ str(self.money))

    def showFatherMoney(self):#定义一个子类独有的方法
        print('我爹有',str(self.money))

#初始化 创建子类实例对象
# rc = RichChild(100000000,8)# 需要传参,因为父类有两个参数
# print('富二代钱 ',rc.money)#富二代钱
# print('富二代公司',rc.company)
#
# rc.earnMoney(1000)
# print('富二代有多少钱',rc.money)
# rc = RichChild(1000000000,8)
# print('刚出生时,富二代自己的钱是',rc.ownMoney)  #0
#
# rc.earnMoney(10000)
# print(rc.ownMoney)#10000
#
# rc.spendMoney(10)
# print(rc.ownMoney)#9990
#
# rc.showMoney() #我有9990
#
# print('我没钱我爹有,富二代剩下的钱:',rc.money)#我没钱我爹有,富二代剩下的钱: 1000000000
# rc.showMoney()#我有9990
# rc.showFatherMoney()#我爹有 1000000000
rm = RichMan(10000,8)
rm.spendMoney(3000)
print(rm.money)

  

 

posted @ 2022-03-30 09:00  碎碎圆圆  阅读(82)  评论(0)    收藏  举报