I am trying to create a python class based on this class. I am trying to have it return the person’s wages for the week (including time and a half for any overtime. I need to place this method following the def getPhoneNo(self): method and before the def __str__(self):
method because I am trying to use this method in another program. I f anyone can help out.
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)
Is the __str__
function looking alright? I mean stringRep is changed several times and the last version is returned.
I think the body of the function should look like this:
stringRep = "First Name: " + self.firstName + "\n" +\
"Last Name: " + self.lastName + "\n" +\
"Phone Number : " + self.phoneNo + "\n"
return stringRep
I see two issues in the example you posted:
- The getWeeksPay function needs to be indented so that it is interpreted as a PersonWorker class method versus a normal function.
- You have some funky characters at the end of the return statement in the str method.
I updated your code snippet with an example of what I think you are trying to accomplish.
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
来源:https://stackoverflow.com/questions/18026306/classes-within-python-part-1