简体   繁体   中英

Python calling function with return statement

I have the below piece that created few person objects and apply some methods on those objects.

class Person:
    def __init__(self, name, age, pay=0, job=None):
        self.name = name
        self.age  = age
        self.pay  = pay
        self.job  = job

    def lastname(self):
        return  self.name.split()[-1]

    def giveraise(self,percent):
        return self.pay *= (1.0 + percent)

if __name__ == '__main__':
    bob = Person('Bob Smith', 40, 30000, 'software')
    sue = Person('Sue Jones', 30, 40000, 'hardware')
    people = [bob,sue]
    print(bob.lastname())
    print(sue.giveraise(.10))

Once I run this program, this is the output--

Syntax Error: Invalid syntax

but when I run using the below code, I don't have any problem,

if __name__ == '__main__':
    bob = Person('Bob Smith', 40, 30000, 'software')
    sue = Person('Sue Jones', 30, 40000, 'hardware')
    people = [bob,sue]
    print(bob.lastname())
    sue.giveraise(.10)
    print(sue.pay)

What is the difference in two cases

*= is an assignment, and assignment is a statement in Python, not an expression. Try:

self.pay *= (1.0 + percent)
return self.pay

I get the invalid syntax error even in the second version; I don't know how you got it to work, but you must have changed the giveraise function. In Python, assignments, including those using mutators like *= , are statements, not expressions; they have no value. Since they have no value, it doesn't make sense to return them from a function, hence the error.

Your problem is this function (I get an error in both cases):

def giveraise(self,percent):
    return self.pay *= (1.0 + percent)

Change it to this and it will work:

def giveraise(self,percent):
    self.pay *= (1.0 + percent)
    return self.pay

I'm not entirely sure why Python throws a syntax error, but I do know that this works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM