0

not able to define variable inside of decorated method

#Not exactly sure why the code is always using 1.2 when I redefine raise_percentage raise_percentage=1.2 class worker: def __init__(self,age,pay): self.age=age self.pay=pay def Raise(func): def wrapper(self): #as you can see I define raise_percentage by the amount I want to increase #wage by but it always refers back to the initial value 1.2. if self.age<30: raise_percentage=1.2 func(self) print("under 30") elif self.age<40: raise_percentage=1.1 func(self) print("under 40") elif self.age<50: raise_percentage=1.05 func(self) print("under 50") else: raise_percentage=1 func(self) print("over 50") return wrapper def func(self): print( self.pay*raise_percentage) Raised=Raise(func) Bob=worker(24,20000) Carl=worker(36,34000) Jessica=worker(43,41000) Jessica.Raised()

27th Dec 2020, 3:27 PM
Sean
Sean - avatar
6 Antworten
+ 4
Never use 'global' with object oriented programming : it is a bad programming practice. Convert 'raise_percentage' to a class variable instead, it would be way better.
27th Dec 2020, 3:52 PM
Théophile
Théophile - avatar
+ 4
Théophile Oh yeah you're right it is. I forgot it is a class. Thanks!
27th Dec 2020, 3:54 PM
noteve
noteve - avatar
+ 3
Add global raise_percentage inside Raise function in order to affect the variable "raise_percentage" because "raise_percentage" is a global variable and global variables are not affected by functions unless you include "global" inside the function like above. I hope this helps. Happy Coding! Here's your code https://code.sololearn.com/c2yeHZOvbE5D/?ref=app
27th Dec 2020, 3:36 PM
noteve
noteve - avatar
+ 1
Thanks so much guys. I'm still pretty new to coding so was confused by this one
27th Dec 2020, 4:45 PM
Sean
Sean - avatar
+ 1
Sean Place the variable inside the class (often at above) outside funcions or methods. Like this Class worker: raise_percentage = 1.2 def __init__ (self, age, pay) ....
27th Dec 2020, 11:07 PM
noteve
noteve - avatar
0
how do i create a class variable?
27th Dec 2020, 4:48 PM
Sean
Sean - avatar