學習總結-《父與子的編程之旅》chapter 14


本章主要講對象。
此篇往后 先只附上代碼示例,內容之后有空再來填補。
示例:

class Hot_dog:
    def __init__(self):
        self.cooked_level = 0
        self.cooked_string = "Raw"
        self.condiments = [  ]

    def __str__(self):
        msg = 'hot dog'
        if len(self.condiments) > 0:
            msg = msg+' with '
        for i in self.condiments:
            msg = msg+i+", "
        msg = msg.strip(", ")
        msg = self.cooked_string+" "+ msg + "."
        return msg

    def cook(self,time):
        self.cooked_level = self.cooked_level+time
        if self.cooked_level > 8:
            self.cooked_string = "Charcoal"
        elif self.cooked_level > 5:
            self.cooked_string = "Well done"
        elif self.cooked_level > 3:
            self.cooked_string = "Medium"
        else:
            self.cooked_string = "Raw"

    def addCondiments(self,condiment):
        self.condiments.append(condiment)

mydog = Hot_dog()
print(mydog)
print("Cooking hot dog for 4 minutes")
mydog.cook(4)
print (mydog)
print ("Cooking hot dog for 3 more minutes")
mydog.cook(3)
print (mydog)
print ("What happends if I cook it for 10 more minutes")
mydog.cook(10)
print (mydog)
print ("Now I'm going to add some stuff on my hot dog")
mydog.addCondiments("ketchup")
mydog.addCondiments("mustard")
print (mydog)

動手試一試:

class BankAccount:
    def __init__(self,name,account,money):
         self.name = name 
         self.account = account
         self.money = money
    def __str__(self):
        msg = str(self.name) +", you have " + str(float(self.money))+" yuan"
        return msg

    def Showmoney(self):
        print("You have"+self.account + "left")
    def Quqian(self,money_q):
        money_q =money_q
        self.money = self.money
        if money_q <  self.money or money_q ==  self.money:
            print("你將取" + str(money_q) + "元")
            self.money = self.money - money_q
        else :
            print("余額不足")
        def Cunqian(self,money_C):
            self.money = self.money + money_C
            print ("您已存款"+money_C +"元")

my = BankAccount("elsa",123,500)
print (my)
my.Showmoney
my.Quqian(200.5)
print (my)

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com