类
class Cat: """定义了一个Cat类""" #初始化对象 def __init__(self,new_name,new_age): self.name = new_name self.age = new_age #方法 def eat(self): print("猫在吃鱼....") def drink(self): print("猫正在喝可乐...") def introduces(self): print("%s的年龄是:%d" % (self.name, self.age)) #创建一个对象 tom = Cat("汤姆",40) #调用tom指向的对象中的方法 tom.eat() tom.drink() #给汤姆指向的对象添加2个属性 # tom.name = "汤姆" # tom.age = 40 tom.introduces() #相当于tom.introduce(tom) xiaohua = Cat("小花",2) # xiaohua.name = "小花" # xiaohua.age = 2 xiaohua.introduces()
__init__()方法
class Cat: """定义了一个Cat类""" #初始化对象 def __init__(self,new_name,new_age): self.name = new_name self.age = new_age def __str__(self): return "%s的年龄是:%d"%(self.name,self.age) #方法 def eat(self): print("猫在吃鱼....") def drink(self): print("猫正在喝可乐...") def introduces(self): print("%s的年龄是:%d" % (self.name, self.age)) #创建一个对象 tom = Cat("汤姆",40) xiaohua = Cat("小花",2) print(tom) #没有改写__str__()方法时,返回的为内存地址 print(xiaohua)
烤地瓜
class SweetPotato: def __init__(self): self.cookedString = "生的" self.cookedLevel = 0 self.condiments = [] def __str__(self): return "地瓜 状态:%s(%d),添加的佐料有:%s"%(self.cookedString,self.cookedLevel,str(self.condiments)) def cook(self,cooked_time): self.cookedLevel+=cooked_time if self.cookedLevel >= 0 and self.cookedLevel < 3: self.cookedString = "生的" elif self.cookedLevel >= 3 and self.cookedLevel < 5: self.cookedString = "半生不熟" elif self.cookedLevel >= 5 and self.cookedLevel < 8: self.cookedString = "熟了" elif self.cookedLevel > 8: self.cookedLevel = "烤糊了" def addCondiments(self,item): self.condiments.append(item) #创建了一个地瓜对象 di_gua = SweetPotato() print(di_gua) #开始烤地瓜 di_gua.cook(1) di_gua.cook(1) di_gua.cook(1) di_gua.addCondiments("大蒜") di_gua.cook(1) print(di_gua)
存放家具
class Home: def __init__(self,new_area, new_info,new_addr): self.area = new_area self.info = new_info self.addr = new_addr self.left_area = new_area self.contain_items = [] def __str__(self): msg = "房子的总面积是:%d,可用面积是:%d,户型是:%s,地址是:%s"%(self.area,self.left_area,self.info,self.addr) msg+=",当前房子里的物品有%s"%(str(self.contain_items)) return msg def addItem(self,item): # self.left_area -= item.area # self.contain_items.append(item.name) self.left_area -= item.get_area() self.contain_items.append(item.get_name()) class Bed: def __init__(self,new_name,new_area): self.name = new_name self.area = new_area def __str__(self): return "%s占用的面积是:%d"%(self.name,self.area) def get_area(self): return self.area def get_name(self): return self.name fangzi = Home(129,"三室一厅","北京市朝阳区长安街666号") print(fangzi) bed1 = Bed("席梦思",4) fangzi.addItem(bed1) print(fangzi) bed2 = Bed("三人床",6) fangzi.addItem(bed2) print(fangzi)