我正在尝试基于这个类创建一个python类。我试图让它返回一周工作人员的工资(包括任何加班时间的一半。我需要在def getPhoneNo(self):方法之后和def __str__(self):
方法之前放置此方法,因为我是试图在另一个程序中使用这种方法。任何人都可以提供帮助。
class PersonWorker: def _init_(self, firstName, lastName, phoneNo): self.firstName= firstName self.lastName= lastName self.phoneNo= phoneNo def getFirstName(self): return self.firstName def getLastName(self): return self.lastName def getPhoneNo(self): return self.phoneNo def _str_(self): stringRep = "First Name: " + self.firstName + "\n" stringRep = "Last Name: " + self.lastName + "\n" stringRep = "Phone Number : " + self.phoneNo + "\n" return stringRep`: def getWeeksPay(self, hours, rate)
答案 0 :(得分:2)
__str__
功能看起来不错吗?我的意思是stringRep被多次更改,并返回最后一个版本。
我认为函数的主体应该如下所示:
stringRep = "First Name: " + self.firstName + "\n" +\
"Last Name: " + self.lastName + "\n" +\
"Phone Number : " + self.phoneNo + "\n"
return stringRep
答案 1 :(得分:1)
我在您发布的示例中看到两个问题:
我更新了您的代码段,其中包含了我认为您要完成的示例。
class PersonWorker:
def __init__(self, firstName, lastName, phoneNo, rate=0):
self.firstName= firstName
self.lastName= lastName
self.phoneNo= phoneNo
self.rate= rate
def getFirstName(self):
return self.firstName
def getLastName(self):
return self.lastName
def getPhoneNo(self):
return self.phoneNo
def getWeeksPay(self,hours):
if rate is 0: raise Exception("Rate not set")
return hours*self.rate
def __str__(self):
stringRep = "First Name: " + self.firstName + "\n"
stringRep += "Last Name: " + self.lastName + "\n"
stringRep += "Phone Number : " + self.phoneNo + "\n"
return stringRep