class Hotdog:
def __init__(self): #初始化对象
self.cooked_level = 0
self.cooked_string ="Raw"
self.condiments = [] #空数组
def __str__(self): #print(对象)
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 + "."+str(self.cooked_level)
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_down"
elif self.cooked_level >=3:
self.cooked_string = "Medium"
else:
self.cooked_string = "Raw"
def addCondiment(self,condiments):
self.condiments.append(condiments)
myDog = Hotdog()
print (myDog)
print ("Cooking hot dog for 4 minutes...")
myDog.cook(4)
print (myDog)
print ("Cooking hot dog for 3 minutes...")
myDog.cook(3)
print (myDog)
print ("Cooking hot dog for 10 minutes...")
myDog.cook(10)
myDog.cooked_level=3 # 这些对象的属性都可以更改,不用通过方法,python 没有提供隐藏数据的方法,不过可以自己搞定。
print (myDog)
print ("Now I'm going to add some stuff on my hot dog")
myDog.addCondiment("ketchup")
myDog.addCondiment("mustard")
print (myDog)
设置私有变量和私有方法可以用__开头
class Person:
def __init__(self):
self.__name = "jixiang"
self.age = 22
def __get_name(self):
return self.__name
def get_name(self):
return self.__name
def get_age(self):
return self.age
def change_name(self):
self.__name = "malong"
return self.__name
def change_name1(self):
self.__name = "jilong" #可以清楚的看到无论是私有属性还是私有方法在类内都可以使用。
newname=self.__get_name()
return newname
person = Person()
print (person.get_age())
#print (person.__get_name()) #无论是私有变量还是私有方法都无法访问。
#print (person.__name)
person.__name ="lilong" #这里虽然没有报错,但是你看下面,打印出来依然没有改变
print (person.get_name())
person.change_name()
print (person.get_name())
person.change_name1()
print (person.get_name())
下面进入多态 ,
封装继承多态是面向对象的重要内容。
多态