Classes within python part 1 [closed]

走远了吗. 提交于 2019-12-02 13:24:06

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!