1、字符串方法
代码块:
class People():
def __init__(self,name):
self.name = name
def __str__(self):
#必须返回一个字符串
return '我是 %s' %(self.name)
p1 = People('老李')
print(p1)
程序及运行结果:
2、字符串方法练习
题目需求:
1.小明和小美都爱跑步
2.小美体重45.0公斤
3.小明体重75.0公斤
4.每次跑步都会减少0.5公斤
5.每次吃东西都会增加1公斤
代码块:
class People():
def __init__(self,name,weight):
self.name = name
self.weight = weight
def __str__(self):
return '我的名字叫%s,体重是%.2f' %(self.name,self.weight)
def run(self):
print('%s爱跑步' %(self.name))
self.weight -= 0.5
def eat(self):
print('%s吃东西' %(self.name))
self.weight += 1
xiaoming = People('小明',75)
xiaoming.run()
print(xiaoming)
xiaomei = People('小美',45)
xiaomei.eat()
print(xiaomei)
程序及运行结果: