It works for Employee and calculate_wage, but returns an error when I try to create an instance of PartTimeEmployee and call to the calculate_wage method of PartTimeEmployee's parent class.
class Employee(object):
"""Models real-life employees!"""
def __init__(self, employee_name):
self.employee_name = employee_name
def calculate_wage(self, hours):
self.hours = hours
return hours * 20.00
class PartTimeEmployee(Employee):
def __init__(self, employee_name):
self.employee_name = employee_name
def calculate_wage(self, hours):
self.hours = hours
return hours * 12.00
def full_time_wage(self, hours):
return super(PartTimeEmployee, self).calculate_wage(self, hours)
milton = PartTimeEmployee("Milton")
print (milton.full_time_wage(10))
return super(PartTimeEmployee, self).calculate_wage(self, hours)
is incorrect, it should be
return super(PartTimeEmployee, self).calculate_wage(hours)
And next time: Also post the error message you're seeing.
Related
Printing entries in a dictionary in descending order so that I can view them according to the example
08:02 - registration
08:45 - doctor checkup
09:00 - procedure
09:15 - doctor checkup
09:25 - radiography
10:30 - blood test
11:00 - doctor checkup
11:30 - hospital discharge
class Time():
def __init__(self, hour, minutes):
self.hour = hour
self.minutes = minutes
def __str__(self):
return "%02d:%02d" % (self.hour, self.minutes)
def __repr__(self):
if self.minutes == 0:
return 'Time({0},{1}0)'.format(self.hour, self.minutes)
return 'Time({0},{1})'.format(self.hour, self.minutes)
class Event():
def __init__(self, time, nameStattion):
self.time = time
self.nameStattion = nameStattion
def __str__(self):
return "{0}-{1}".format(self.time, self.nameStattion)
def __repr__(self):
return 'Event(Time(%d,%d),"%s")' % (self.time.hour, self.time.minutes, self.nameStattion)
class MedicalRecord():
data = {}
def __init__(self, name, id):
self.name = name
self.id = id
def __repr__(self):
return 'Event(Time(%d,%d),"%s")' % (self.time.hour, self.time.minutes, self.nameStattion)
def add(self, time, station):
self.data[time] = Event(Time(int(time[0:2]), int(time[3:5])), station)
def view(self):
#for i in range(len(self.data)):
print(eval(repr(self.data)))
time1 = Time(8, 2)
time1
print(time1)
time2 = eval(repr(time1))
print(time2)
event1 = Event(time1, 'registration')
event1
event2 = eval(repr(event1))
print(event2)
record1 = MedicalRecord('David', 1)
record1.add('08:02', 'registration')
print(record1.data)
record1.add('09:15','doctor checkup')
record1.add('08:45','doctor checkup')
record1.add('09:00','procedure')
record1.add('11:00','doctor checkup')
record1.add('09:25','radiography')
record1.add('11:30','hospital discharge')
record1.add('10:30','blood test')
record1.view()
In my example it prints as one side list
You would want to use the python sorted() function. It will have a key argument which you can pass a function that returns the time and python will sort the list according to that. From there you will probably get an ascending list which you can just do list.reverse() to make it descending.
Edit: actully sorted lets you choose if its acending or decending using the "reverse" argument. See the sorted link for more info.
def keyFunc(EventObj): return f'{EventObj.time}'
sortedList = sorted(SomeEventList, key=keyFunc, reversed = True)
def view(self):
for key in sorted(self.data):
print(key, '-', self.data[key])
Doing an assignment and can't get a variable passed between two methods in the same class.
global check
wage = 0
hours = 0
check = 0
class employee:
def __init__(self, name, wage, hours, check):
self.name = name
self.wage = wage
self.hours = hours
self.check = check
def paycheck(self):
if self.hours > 41:
self.hours = self.hours - 40
overtime = self.wage * self.hours * 1.5
self.check = (40 * self.wage) + overtime
return self.check
#print(self.check)
else:
self.check = self.hours * self.wage
return self.check
#print(self.check)
def __str__(self):
return self.name + ":\n Net Pay: $" + str(self.check)
A_emp = employee("Alice", 20, 40, 0)
B_emp = employee("Bob", 15, 50, 0)
print(A_emp)
print(B_emp)
The output should display the 'Net Pay' of each employee, and works to display most of the str method:
Alice:
Net Pay: $0
Bob:
Net Pay: $0
However, the check variable just wont pass values between class methods. I've globalized it, defined it outside of the class, and tried different variations of self.check vs check. Feel like I'm just throwing things and nothing is sticking. Thanks for any help.
You forgot to call the paycheck() method. Also get rid of your global variables and return statements.
class employee:
def __init__(self, name, wage, hours, check):
self.name = name
self.wage = wage
self.hours = hours
self.check = check
def paycheck(self):
if self.hours > 41:
self.hours = self.hours - 40
overtime = self.wage * self.hours * 1.5
self.check = (40 * self.wage) + overtime
else:
self.check = self.hours * self.wage
def __str__(self):
return self.name + ":\n Net Pay: $" + str(self.check)
A_emp = employee("Alice", 20, 40, 0)
B_emp = employee("Bob", 15, 50, 0)
A_emp.paycheck()
B_emp.paycheck()
print(A_emp)
print(B_emp)
Output:
Alice:
Net Pay: $800
Bob:
Net Pay: $825.0
Once you create the class object you need to call
A_emp.paycheck()
B_emp.paycheck()
I'm learning about OOP and I need some help with defining one of the methods under Album, specifically total_runtime.
Here's some code (verified, all correct) on the context of the question.
class Duration(object):
def __init__(self, minutes, seconds):
self.total_seconds = minutes * 60 + seconds
self.minutes = int(self.total_seconds / 60)
self.seconds = self.total_seconds % 60
def get_minutes(self):
return self.minutes
def get_seconds(self):
return self.seconds
def __str__(self):
# returns the string representation of the Duration in "mm:ss" form.
if len(str(self.minutes)) < 2:
self.minutes = "0" + str(self.minutes)
if len(str(self.seconds)) < 2:
self.seconds = "0" + str(self.seconds)
return str(self.minutes) + ":" + str(self.seconds)
def __add__(self, duration):
#Adds 2 durations together
return Duration(self.minutes + duration.minutes, self.seconds + duration.seconds)
class Song(object):
def __init__(self, artist, title, duration):
self.artist = artist
self.title = title
self.duration = duration
def get_artist(self):
return self.artist
def get_title(self):
return self.title
def get_duration(self):
return self.duration
class Album(object):
def __init__(self, artist, title):
self.artist = artist
self.title = title
self.songs = list()
def add_song(self, song):
# Adds song (of class Song) to the album.
self.songs.append(song)
I need some help with defining the property total_runtime(self) under class Album which is supposed to return the total runtime (of class Duration) of the album.
Here's what I have now. I tried iterating through the album to get the durations of all the songs. Somehow I'm getting an error which says that add is not defined.
def total_runtime(self):
duration = (0,0)
for song in self.songs:
__add__(self, duration)
return duration
Would really appreciate any help debugging! Thank you!
You need to call __add__ as an attribute of the class, the self argument is the object you're calling from. It's implicitly moved into the arguments.
def total_runtime(self):
duration = Duration(0,0)
for song in self.songs:
duration.__add__(song.get_duration())
return duration
But really, __add__ is more cleanly used with the plus operator:
def total_runtime(self):
duration = Duration(0,0)
for song in self.songs:
duration += song.get_duration()
return duration
I am learning about Class Inheritance and overriding methods in python. To implement my learning, I wrote this code to let me better understand how Inheritance and Overriding works. But as I ran the code, I faced this error
"RecursionError: maximum recursion depth exceeded while calling a Python object"
I have tried to increase the recursion limit to 10000, but doing so, Python interpreter stopped working in my local machine. Can anyone help me with how I can overcome the error to have my expected output?
As I am new to the community, I may lack the appropriate presentation of the problem. Feel free to ask for more detailed information about the problem.
# Increasing Recursion Limit
import sys
sys.setrecursionlimit(10000)
import random
# Parent Class
class Unique_id_creator():
def __init__(self, birthdate, birthmonth, birthyear):
self.date = birthdate
self.month = birthmonth
self.year = birthyear
def random_digits(self):
last_two_digits = random.randrange(10, 99)
return self.random_digits()
def unique_id(self):
id = int(self.date + self.month + self.year + self.random_digits())
return self.unique_id()
# Child Class
class Unique_id_distributer(Unique_id_creator):
def __init__(self, name, birthdate, birthmonth, birthyear):
Unique_id_creator.__init__(self, birthdate, birthmonth, birthyear)
self.name = name
def unique_id(self):
Unique_id_creator.unique_id(self)
return "Dear "+ str(self.name) + ", Your Unique Id is: "+ str(self.unique_id())
citizen1 = Unique_id_distributer("hasan", "01", "11", "2000")
print(citizen1.unique_id())
# Output Window
RecursionError: maximum recursion depth exceeded while calling a Python object
This line return self.random_digits() and this line return self.unique_id() are infinite recursive loops.
I assume what you intended to return was last_two_digits and id.
When you return a function call, that function has to execute to return the result of its call. Since you are calling the function you are executing it continues calling itself forever.
Corrected code
# Increasing Recursion Limit
import sys
sys.setrecursionlimit(10000)
import random
# Parent Class
class Unique_id_creator:
def __init__(self, birthdate, birthmonth, birthyear):
self.date = birthdate
self.month = birthmonth
self.year = birthyear
def random_digits(self):
last_two_digits = random.randrange(10, 99)
# convert to a string since you are concatenating the result
return str(last_two_digits)
def unique_id(self):
id = int(self.date + self.month + self.year + self.random_digits())
return id
# Child Class
class Unique_id_distributer(Unique_id_creator):
def __init__(self, name, birthdate, birthmonth, birthyear):
Unique_id_creator.__init__(self, birthdate, birthmonth, birthyear)
self.name = name
def unique_id(self):
id = Unique_id_creator.unique_id(self)
return "Dear "+ str(self.name) + ", Your Unique Id is: "+ str(id)
citizen1 = Unique_id_distributer("hasan", "01", "11", "2000")
print(citizen1.unique_id())
Additionally, you can eliminate the full call of your parent class by using super().
Child class example
# Child Class
class Unique_id_distributer(Unique_id_creator):
def __init__(self, name, birthdate, birthmonth, birthyear):
super().__init__(birthdate, birthmonth, birthyear)
self.name = name
def unique_id(self):
id = super().unique_id()
return "Dear "+ str(self.name) + ", Your Unique Id is: "+ str(id)
The Product class seems to work fine but I'm trying to figure out how to get the Inventory class to separate each product into there specific categories. I feel like I'm close but whenever I try and print out the inventory it just shows where it's stored in memory and doesn't actually print anything out. The output i receive when running is at the bottom. I want it to print out the actual products and data, not the instance of it stored in memory.
class Product:
def __init__(self, pid, price, quantity):
self.pid = pid
self.price = price
self.quantity = quantity
def __str__(self):
#Return the strinf representing the product
return "Product ID: {}\t Price: {}\t Quantity: {}\n".format(self.pid, self.price, self.quantity)
def get_id(self):
#returns id
return self.pid
def get_price(self):
#returns price
return self.price
def get_quantity(self):
#returns quantity
return self.quantity
def increase_quantity(self):
self.quantity += 1
def decrease_quantity(self):
self.quantity -= 1
def get_value(self):
value = self.quantity * self.price
return 'value is {}'.format(value)
product_1 = Product('fishing', 20, 10)
product_2 = Product('apparel', 35, 20)
class Inventory:
def __init__(self, products):
self.products = products
self.fishing_list = []
self.apparel_list = []
self.value = 0
def __repr__(self):
return "Inventory(products: {}, fishing_list: {}, apparel_list: {}, value: {})".format(self.products, self.fishing_list, self.apparel_list, self.value)
def add_fishing(self):
for product in self.products:
if product.get_id() == 'fishing':
self.fishing_list.append(product)
return '{} is in the fishing section'.format(self.fishing_list)
def add_apparel(self):
for product in self.products:
if product.get_id() == 'apparel':
self.apparel_list.append(product)
return '{} is in the apparel section'.format(self.apparel_list)
inventory_1 = Inventory([product_1, product_2])
inventory_1.add_fishing()
print(inventory_1)
OUTPUT = Inventory(products: [<main.Product instance at 0x10dbc8248>, <main.Product instance at 0x10dbc8290>], fishing_list: [<main.Product instance at 0x10dbc8248>], apparel_list: [], value: 0)
You need to specify how an object of the class Inventory should be printed.
To do this you need to implement at least one of the following functions in your class.
__repr__
__str__
This answer helps, which of both you should use: https://stackoverflow.com/a/2626364/8411228
An implementation could look something like this:
class Inventory:
# your code ...
def __repr__(self):
return str(self.products) + str(self.fishing_list) + str(self.apparel_list) + str(self.value)
# or even better with formatting
def __repr__(self):
return f"Inventory(products: {self.products}, fishing_list: {self.fishing_list}, apparel_list: {self.apparel_list}, value: {self.value})
Note that I used in the second example f strings, to format the output string.