我目前正在参加python课程,并且正在使用Codegrinder进行一些让我感到悲伤的练习。我有以下课程:
MAX_LEAD_LENGTH = 10
MAX_NUM_LEADS = 5
class Pencil:
def __init__(self, num_leads):
self.mNumLeads = 0
self.mCurrentLeadLength = MAX_LEAD_LENGTH
self.addLeads(num_leads)
return
def getNumLeads(self):
return self.mNumLeads
def getCurrentLeadLength(self):
return self.mCurrentLeadLength
def click(self):
if self.mCurrentLeadLength > 0:
self.mCurrentLeadLength -= 1
if self.mCurrentLeadLength == 0 and self.mNumLeads > 0:
self.mCurrentLeadLength = MAX_LEAD_LENGTH
self.mNumLeads -= 1
return self.mCurrentLeadLength > 0
def addLeads(self, num_additional_leads):
if num_additional_leads > 0:
self.mNumLeads += num_additional_leads
if self.mNumLeads > MAX_NUM_LEADS:
self.mNumLeads = MAX_NUM_LEADS
return self.mNumLeads
说明如下:
练习:query01
描述的
在本练习中,您将创建一个接收Pencil对象作为参数的函数。它将返回铅笔中当前铅的长度。
功能名称
query01
参数
- 铅笔:铅笔对象
返回值
- 铅笔当前铅的长度。
实施例
p = Pencil(3) p.click() query01(p) -> a number representing the length
如何编写此函数以接收对象作为函数中的参数?
答案 0 :(得分:1)
您的作业不以返回方法。相反,它是返回当前长度。您已 此功能为 getCurrentLeadLength
。
该对象已作为 self
参数进入方法。
现在,对于给定的界面,您可能需要更改几个名称,但这实际上是伪装的 getCurrentLeadLength
。