前置条件:本文章是Python3,该文章讲解同类中方法的互相调用
一、同类中方法互相调用(基础理解)
首先理解在python中,如何进行同类中方法互相调用呢,请看如下
class MyCount:
#方法1:该方法调用了方法2的两个值,并让他们相乘
def multiply(self):
mysum=self.num1 * self.num2
print(mysum)
#方法2:该方法传入2个值
def mynum(self,a1,a2):
self.num1=a1
self.num2=a2
test=MyCount()
# 给mynum方法传入值10和20
test.mynum(10,20)
# 使用方法1,即可以计算10和20相乘结果
test.Multiply()
以上,理解了吗?就是multiply方法调用了mynum方法。
二、同类中,互相调用练习题
接下来开始做练习题了:
题目:烤地瓜,用python实现,自由烤多少分钟,过程中可以添加佐料,最后打印出来地瓜的状态和累计的佐料。
[0,3)分钟表示生的,[3,5)表示半生不熟,[5,8)表示熟了, [8,+∞)表示糊了。
解题步骤1:
class SweetPotato:
#初始化方法,默认地瓜状态cookedstatus为生的
def __init__(self):
self.cookedstatus='生的'
def cook(self,time):
if time>=0 and time<3:
self.cookedstring='生的'
elif time>=3 and time<5:
self.cookedstring='半生不熟'
elif time>=5 and time<8:
self.cookedstring='熟了'
elif time>=0 and time<3:
self.cookedstring='糊了'
digua=SweetPotato()
digua.cook(3)
print(digua.cookedstring)
运行结果:
你会发现,这代码无法满足需求,无法累加烹饪次数。而且每次还要调用方法,应该放到描述信息方法里面去,这样只要直接打印对象就可以了
步骤2,添加描述信息方法
class SweetPotato:
#初始化方法,默认地瓜状态cookedstatus为生的
def __init__(self):
self.cookedstatus='生的'
#添加描述信息方法
def __str__(self):
return '地瓜的状态是%s' % self.cookedstatus
def cook(self,time):
if time>=0 and time<3:
self.cookedstring='生的'
elif time>=3 and time<5:
self.cookedstring='半生不熟'
elif time>=5 and time<8:
self.cookedstring='熟了'
elif time>=0 and time<3:
self.cookedstring='糊了'
digua=SweetPotato()
digua.cook(3)
#直接打印对象就可以了,不用调用方法
print(digua)
运行结果:
步骤3,累加烹饪次数
以上的代码,明明已经累加了烹饪次数,但是为何运行结果还是生的?这段代码的问题出在哪里??
正确的步骤3:
class SweetPotato:
def __init__(self):
self.cookedstatus='生的'
self.cookedlevel=0
def __str__(self):
return '地瓜的状态是%s,烹饪程度是%d' % (self.cookedstatus,self.cookedlevel)
def cook(self,time):
self.cookedlevel += time
if self.cookedlevel>=0 and self.cookedlevel<3:
self.cookedstatus='生的'
elif self.cookedlevel>=3 and self.cookedlevel<5:
self.cookedstatus='半生不熟'
elif self.cookedlevel>=5 and self.cookedlevel<8:
self.cookedstatus='熟了'
elif self.cookedlevel>=8:
self.cookedstatus='糊了'
digua=SweetPotato()
digua.cook(5)
print(digua)
运行结果:
到这里,这道题目就完成了。现在再把题目改一下,可以给地瓜添加佐料。addCondiments表示添加佐料:
步骤4:最后答案,添加佐料
class SweetPotato:
def __init__(self):
self.cookedstatus='生的'
self.cookedlevel=0
self.condiments=[]
def __str__(self):
return '当前状态是%s,烹饪程度是%d,累计添加佐料有:%s' % (self.cookedstatus,self.cookedlevel,str(self.condiments))
def cook(self,time):
self.cookedlevel+=time
if self.cookedlevel>=0 and self.cookedlevel<3:
self.cookedstatus='生的'
elif self.cookedlevel>=3 and self.cookedlevel<5:
self.cookedstatus='半生不熟'
elif self.cookedlevel>=5 and self.cookedlevel<8:
self.cookedstatus='熟了'
elif self.cookedlevel>=8:
self.cookedstatus='糊了'
def addCondiments(self,condiment):
self.condiments.append(condiment)
digua=SweetPotato()
digua.cook(2)
digua.addCondiments('番茄酱')
digua.cook(2)
digua.addCondiments('辣椒酱')
digua.cook(2)
print(digua)
运行结果:
原文链接:https://blog.csdn.net/doris_9800/article/details/105064288