This is my code:
w1 = ch8.Worker("Joe", 15)
print(w1.pay(35)) # Not implemented
w2 = ch8.SalariedWorked("Sue", 14.50)
print(w2.pay()) # 580.0
print(w2.pay(60)) # 580.0
w3 = ch8.HourlyWorker("Dana", 20)
print(w3.pay(25)) # 500
w3 = changeRate(35)
print(w3.pay(35)) # 875
And this is the classes Worker, SalarieWorked and HourlyWorker that I implemented in the file ch8.py:
class Worker:
def __init__(self, worker_name="Unknown", hourly_pay_rate=0.0):
self.worker_name = str(worker_name)
self.hourly_pay_rate = float(hourly_pay_rate)
def changeRate(self, new_pay_rate):
self.new_pay_rate = float(new_pay_rate)
self.hourly_pay_rate = self.new_pay_rate
def pay(self, number_of_hours):
self.number_of_hours = number_of_hours
return "Not implemented"
class HourlyWorker(Worker):
def pay(self, number_of_hours):
self.number_of_hours = int(number_of_hours)
if self.number_of_hours > 40:
return (
40 * self.hourly_pay_rate
+ (self.number_of_hours - 40) * self.hourly_pay_rate * 2
)
return self.number_of_hours * self.hourly_pay_rate
class SalariedWorked(Worker):
def pay(self, number_of_hours=40):
self.number_of_hours = int(number_of_hours)
return 40 * self.hourly_pay_rate
This is what I get when I execute the code:
Not implemented
580.0
580.0
500.0
Traceback (most recent call last):
File "C:\\Users\\carol\\PycharmProjects\\ProblemasPraticos\\book_Intro_Computing_Using_Python\\Chapter 8\\8_Exercises.py", line 137, in
w3 = changeRate(35)
NameError: name 'changeRate' is not defined
Someone could help me to understand why this error?
Thanks!
you write w3.pay(25)
w3 = changeRate(35)
why not w3.changeRate(35)
You are overriding the function.
When you call w3 = ch8.HourlyWorker("Dana", 20)
you are creating an object w3 of type HourlyWorker.
Then you are assigning a function to the class object when you write w3 = changeRate(35)
This is not permitted.
Try doing just w3.changeRate(35)
instead of **w3 = changeRate(35)**
changeRate
is a method of Worker
class, so to use it, you need to call it from class instanse
Exsample:
w3.changeRate(35)
changeRate()
is a method of the class Worker
. So, you have to call it through an instance of the class. The class HourlyWorker
inherits from the class Worker
. So the method changeRate()
is available in the class HourlyWorker
.
To achieve your goal, replace the line w3 = changeRate(35)
by this line: w3.changeRate(35)
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.