- 要求:
(1)创建狗类:Dog()
(2)Dog类具有:
实例属性:name(名字)、type(类型)、color(颜色)、love_food(喜欢吃的食物)
eat_num(吃食物的次数)
实例方法:使用__init__方法进行初始化
str 输出:xxx是xx颜色xx类型的小狗,喜欢吃xxx
eat() 说明:吃一次食物,eat_num加1
class Dog():
def __init__(self):
self.name = "大帅"
self.type = "牧羊犬"
self.color = "白色"
self.love_food = "骨头"
def eat_num(self,eat):
print("吃食物的次数是%d" % eat)
def __str__(self):
return"%s是%s颜色%s类型的小狗,喜欢吃%s" % (self.name,self.color,self.type,self.love_food)
dog = Dog()
dog.eat_num(1)
print(dog)
-
定义一个水果类(Fruit):
有3个实例属性: 1.名字name,2.价格price,3.重量 weight
有以下实例方法:
1:获取水果名:getName()
2:获取水果总价:getTotal()(总价=价格x重量)
3:获取水果信息:getInfo(),输出内容为:xxx的单价是yyy,其中xxx是名称,yyy是单价
4:获取水果的成本:getCost()(苹果的成本在总价上加100元,石榴的成本在总价上加80元)
定义两个水果对象,名字必须是苹果和石榴,调用上述方法,比较二者的成本价,并打印结果。class Fruit: def __init__(self,name,price,weight): self.name = name self.price = price self.weight = weight def getName(self): return self.name def getTotal(self): return self.price * self.weight def getInfo(self): print("%s的单价是%.2f,其中%s是名称,%.2f是单价" %(self.name,self.price,self.name,self.price)) def getCost(self,cost): print("%s的成本价是%.2f" % (self.name,self.getTotal() + cost)) apple = Fruit("苹果",4,10) shiliu = Fruit("石榴",9.5,8) apple.getInfo() apple.getCost(100) shiliu.getInfo() shiliu.getCost(80)