Calling variable from another class in “python” - python

Good day Sir,
I have a problem in calling the variable date, group from class JB() and KL() because I want to compare if the group in JB and KL is 1 and the date for JB()==KL(), I want to print the date. I have tried some solution from this forum, but it seems like I have failed.
class JB(object):
def __init__(self, date, timeslot, group):
self.date = date
self.timeslot = timeslot
self.group = group
def timetableJB(self):
print(self.date)
tt1 = JB("8 Sept", (TS3_JB, TS4_JB, TS5_JB, TS6_JB), G1)
tt2 = JB("15 Sept", (TS3_JB, TS4_JB, TS5_JB, TS6_JB), G2)
tt3 = JB("22 Sept", (TS3_JB, TS4_JB, TS5_JB, TS6_JB), G3)
class KL(object):
def __init__(self, date, timeslot, group):
self.date = date
self.timeslot = timeslot
self.group = group
def timetableKL(self):
print(self.date, self.timeslot, self.group)
tt2 = KL("15 Sept", (TS1_KL, TS2_KL, TS3_KL), G1)
tt3_1 = KL("22 Sept", (TS1_KL, TS2_KL, TS3_KL), G2)
tt3_2 = KL("23 Sept", (TS4_KL, TS5_KL, TS6_KL), G3)
class PP(object):
def __init__(self, date, timeslot, group):
self.date = date
self.timeslot = timeslot
self.group = group
def timetablePP(self):
print(self.date, self.timeslot, self.group)
tt3 = PP("22 Sept", (TS1_PP, TS2_PP, TS3_PP), G1)
tt4_1 = PP("29 Sept", (TS1_PP, TS2_PP, TS3_PP), G2)
tt4_2 = PP("30 Sept", (TS4_PP, TS5_PP, TS6_PP), G3)
print("")
print("Clash analysis for timetable KL and JB")
clashJB = JB()<----- I have error in this part
clashKL = KL()<----- I have error in this part
while clashJB.group and clashKL.group == G1:
if clashJB.date == clashKL.date:
print(clashJB.date)

You might be getting error because you are trying to create instances clashJB and clashKL without passing mandatory parameters date, timeslot, group . You need to create it as:
clashJB = JB(<date>, <timeslot>, <group>)
clashKL = KL(<date>, <timeslot>, <group>)
before you perform comparison operations.
You can go through https://docs.python.org/2/tutorial/classes.html if you have any doubts related to class definition and its use.

Following code work as per your expectation .
class JB(object):
def __init__(self, date, timeslot, group):
self.date = date
self.timeslot = timeslot
self.group = group
def timetableJB(self):
print(self.date)
class KL(object):
def __init__(self, date, timeslot, group):
self.date = date
self.timeslot = timeslot
self.group = group
def timetableKL(self):`enter code here`
print(self.date, self.timeslot, self.group)
class PP(object):
def __init__(self, date, timeslot, group):
self.date = date
self.timeslot = timeslot
self.group = group
def timetablePP(self):
print(self.date, self.timeslot, self.group)
clashJB = JB(1,2,'G1')<---- Note the change
clashKL = KL(1,2,'G1')<-----Note the change
while clashJB.group and clashKL.group == 'G1':
if clashJB.date == clashKL.date:
print(clashJB.date)

Related

How to check if 2 elements are same in python OOP?

class Course:
def __init__(self, name, classroom, instructor, day, start_time, end_time):
self.name = name
self.classroom = classroom
self.instructor = instructor
self.day = day
self.start_time = start_time
self.end_time = end_time
class Schedule:
def __init__(self):
self.courses = []
program = [["9","10","11","12","13","14","15","16","17"],["9","10","11","12","13","14","15","16","17"],["9","10","11","12","13","14","15","16","17"],["9","10","11","12","13","14","15","16","17"],["9","10","11","12","13","14","15","16","17"]]
def add_course(self, course):
self.courses.append(course)
def print_schedule(self):
days = ["Monday","Tuesday","Wednesday","Thursday","Friday"]
program = [["9","10","11","12","13","14","15","16","17"],["9","10","11","12","13","14","15","16","17"],["9","10","11","12","13","14","15","16","17"],["9","10","11","12","13","14","15","16","17"],["9","10","11","12","13","14","15","16","17"]]
for course in self.courses:
for j in range(course.start_time-9,course.end_time-8):
program[days.index(course.day)][j] += f" {course.name} class from {course.instructor} at {course.classroom}"
for i in range(len(days)):
print(days[i],":")
for k in program[i]:
print(k)
schedule = Schedule()
schedule.add_course(Course("Physics","MED A11","James","Monday",9,11))
schedule.add_course(Course("Logic Design","EEB 4105","Jack","Wednesday",9,10))
schedule.add_course(Course("Logic Design","EEB 4205","Jack","Wednesday",15,17))
schedule.print_schedule()
Here I wanted to create an weekly schedule, I want it to write something when two classes collide. So their self.day need to be same and the times need to intersect.
For times I can do something like
time = {for i in range(start_time,end_time+1)}
if time1.intersection(time2) != 0:
#...
But I don't know how to reach 2 different Course elements at the same time. Also would be great if you have any suggestions for this code.
You can add a method to the Course class that checks it against another Course to see if they collide. When you add a course, have it loop through the existing courses to see if it collides with the existing courses in your Schedule.
class Course:
def __init__(self, name, classroom, instructor, day, start_time, end_time):
self.name = name
self.classroom = classroom
self.instructor = instructor
self.day = day
self.start_time = start_time
self.end_time = end_time
def check_collision(self, other):
if self.day == other.day:
if other.start_time < self.start_time < other.end_time:
return True
if other.start_time < self.end_time < other.end_time:
return True
if self.start_time < other.start_time < self.end_time:
return True
if self.start_time < other.end_time < self.end_time:
return True
return False
class Schedule:
def __init__(self):
self.courses = []
self.program = [
["9","10","11","12","13","14","15","16","17"],
["9","10","11","12","13","14","15","16","17"],
["9","10","11","12","13","14","15","16","17"],
["9","10","11","12","13","14","15","16","17"],
["9","10","11","12","13","14","15","16","17"],
]
def add_course(self, course):
for c in self.courses:
if course.check_collision(c):
print(f'New course has collision with course: {c.name} on {c.day}: {c.start_time}-{c.end_time}')
break
else:
self.courses.append(course)
def print_schedule(self):
days = ["Monday","Tuesday","Wednesday","Thursday","Friday"]
program = [x.copy() for x in self.program]
for course in self.courses:
for j in range(course.start_time-9,course.end_time-8):
program[days.index(course.day)][j] += f" {course.name} class from {course.instructor} at {course.classroom}"
for i in range(len(days)):
print(days[i],":")
for k in program[i]:
print(k)
So based on your Code, what you can do is define a compare function for the class Schedule, you make a Schedule object to hold many courses. So if you want to access a course within a Schedule you need to do schedule.courses[i]. But I suggest you add the following function to the courses class to solve your problem.
def compare_course(self, other_course):
my_time = {i for i in range(start_time, end_time+1)}
other_time = {i for i in range(other_course.start_time, other_course.end_time+1)}
if my_time.intersection(other_course.time) != set():
return "Course Collides"
else:
return "Course does not collide"

Calculations in class Student

I have created two classes: Person and Student in different modules. Here is my class Person:
import datetime
class Person:
def __init__(self, name, surname, patronymic, birthdate):
self.name = name
self.surname = surname
self.patronymic = patronymic
self.birthdate = birthdate
def age(self):#this function calculates age of person
today = datetime.date.today()
age = today.year - self.birthdate.year
if today < datetime.date(today.year, self.birthdate.month, self.birthdate.day):
age -= 1
return age
Here is my class Student:
from ClassPerson import Person
class Student(Person):
number_of_group = eval(input("\nInput number of group: "))
summa = 0
amount_of_students = 0
overall_age = 0
def __init__(self, name, surname, patronymic, birthdate, faculty, group, scholarship):
Person.__init__(self, name, surname, patronymic, birthdate)
self.faculty = faculty
self.group = group
self.scholarship = scholarship
if Student.number_of_group == self.group:
Student.summa += self.scholarship
Student.overall_age += Student.age(self)
Student.amount_of_students += 1
#property
def scholarship(self):
return self.__scholarship
#scholarship.setter
def scholarship(self, new_s):
if new_s < 1300:
self.__scholarship = 1300
elif new_s > 4000:
self.__scholarship = 4000
else:
self.__scholarship = new_s
I have one simple problem: I need to calculate for specific group overall sum of scholarships and middle age of students of this group. I do calculations in def __init__. But i also had property and setter to change the amount of scholarship due to conditions. So for example we have 3 students:
student1 = Student(
"Joe",
"Hapfy",
"Canes",
datetime.date(1992, 3, 12),
"Philosophy faculty",
441,
4300
)
student2 = Student(
"Jane",
"Mers",
"Rodrigo",
datetime.date(1998, 4, 29),
"Historical faculty",
441,
2700
)
student3 = Student(
"Pavlo",
"Hornov",
"Andriyovich",
datetime.date(1997, 7, 22),
"Mathematics faculty",
171,
1300
)
I want to change student1 scholarship. For example:
student1.scholarship = 1500
print(student1.scholarship)
But the changes are not saved, cause i do calculations in dev __init__. For example, I input number of group as 441.
result = Student.overall_age/Student.amount_of_students
print("Total sum of scholarships: %d" % Student.summa)
The sum of scholarships will be 4300+2700, but due to setter 4300 will be changed to 4000 and sum will be 6700. But now my student1 scholarship is 1500 and i want to receive result 1500+2700=4200. How can i do such calculations after changes of scholarship? Should I use method or something like that instead of calculations in dev __init__?
The property setter needs to update Student.summa when necessary.
Since the setter needs to read the old value, we can't use it before we initialize the internal __scholarship attribute. So the __init__() method needs to assign directly to the internal attribute, rather than using the setter with self.scholarship.
from ClassPerson import Person
class Student(Person):
number_of_group = eval(input("\nInput number of group: "))
summa = 0
amount_of_students = 0
overall_age = 0
def __init__(self, name, surname, patronymic, birthdate, faculty, group, scholarship):
Person.__init__(self, name, surname, patronymic, birthdate)
self.faculty = faculty
self.group = group
self.__scholarship = scholarship
if Student.number_of_group == self.group:
Student.summa += self.scholarship
Student.overall_age += Student.age(self)
Student.amount_of_students += 1
#property
def scholarship(self):
return self.__scholarship
#scholarship.setter
def scholarship(self, new_s):
old_s = self.__scholarship
if new_s < 1300:
self.__scholarship = 1300
elif new_s > 4000:
self.__scholarship = 4000
else:
self.__scholarship = new_s
# Adjust Student.summa by the change in scholarship
if self.group == Student.number_of_group:
Student.summa += self.__scholarship - old_s

Python Class Function not defined

I'm creating a class with function within,
but i keep getting error "name 'direct_report' is not defined"
Basically im tring to make an organization chart, creating a list using the direct_report function to add people under each position
class employee:
def __init__(self, name , title, salary):
self.name = name
self.title = title
self.salary = salary
self.direct_reports_list = direct_report()
def __str__(self):
#otheremp_list = []
print(self.title,'-', self.name)
print('Direct Reports:')
for emp in self.direct_reports_list:
print(emp.title,'-', emp.name)
# otheremp_list.append(emp.direct_reports_list)
#print('other employees:')
#for emp in otheremp_list:
# print(emp.title,'-', emp.name)
# otheremp_list.append(emp.direct_reports_list)
def direct_report(self,value):
print(value)
direct_reports_list = []
direct_reports_list.append(value)
print(direct_reports_list)
return direct_reports_list
ceo = employee("Elon Musk", "CEO",1000000)
devdir = employee("Jeff Bezos","Development Director",500000)
devassoc1 = employee("Beyonce Knowles","Development Associate", 50000)
devassoc2 = employee("Taylor Swift","Development Associate", 50000)
ceo.direct_report(devdir)
ceo.direct_report(devdir2)
devdir.direct_report(devassoc1)
devdir.direct_report(devassoc2)
print(ceo)
The # is my further plan to print the full organization chart, but currently im still stuck at the "direct report" parts
You need to add one indentation level for the classes methods like that:
class employee:
def __init__(self, name , title, salary):
self.name = name
self.title = title
self.salary = salary
self.direct_reports_list = direct_report()
def __str__(self):
#otheremp_list = []
print(self.title,'-', self.name)
print('Direct Reports:')
for emp in self.direct_reports_list:
print(emp.title,'-', emp.name)
# otheremp_list.append(emp.direct_reports_list)
#print('other employees:')
#for emp in otheremp_list:
# print(emp.title,'-', emp.name)
# otheremp_list.append(emp.direct_reports_list)
def direct_report(self,value):
print(value)
direct_reports_list = []
direct_reports_list.append(value)
print(direct_reports_list)
return direct_reports_list
ceo = employee("Elon Musk", "CEO",1000000)
devdir = employee("Jeff Bezos","Development Director",500000)
devassoc1 = employee("Beyonce Knowles","Development Associate", 50000)
devassoc2 = employee("Taylor Swift","Development Associate", 50000)
ceo.direct_report(devdir)
ceo.direct_report(devdir2)
devdir.direct_report(devassoc1)
devdir.direct_report(devassoc2)
print(ceo)
Call the function in this way.
class employee:
def __init__(self, name , title, salary):
self.name = name
self.title = title
self.salary = salary
self.direct_reports_list = self.direct_report()
try self.direct_report() instead as you are calling a method within the class
Try this code.
class employee:
def __init__(self, name , title, salary):
self.name = name
self.title = title
self.salary = salary
self.direct_reports_list = []
def __str__(self):
#otheremp_list = []
print(self.title,'-', self.name)
print('Direct Reports:')
for emp in self.direct_reports_list:
print(emp.title,'-', emp.name)
# otheremp_list.append(emp.direct_reports_list)
#print('other employees:')
#for emp in otheremp_list:
# print(emp.title,'-', emp.name)
# otheremp_list.append(emp.direct_reports_list)
return "Done"
def direct_report(self,value):
self.direct_reports_list.append(value)
ceo = employee("Elon Musk", "CEO",1000000)
devdir = employee("Jeff Bezos","Development Director",500000)
devassoc1 = employee("Beyonce Knowles","Development Associate", 50000)
devassoc2 = employee("Taylor Swift","Development Associate", 50000)
ceo.direct_report(devdir)
devdir.direct_report(devassoc1)
devdir.direct_report(devassoc2)
print(ceo)
print(devdir)
print(devassoc1)
print(devassoc2)

Python Composite Class JSON Serialization

I have what I would term a composite class
Whereby the class LegoSet is constructed from an instantiation of the class LegoSetVariant and inturn the class LegoSetVariant is constructed from a number of different class instantiations.
This is fine and I can successfully initialize the class. However, I then want to serialize the class object into JSON. This is proving a bit tricky as the composite classes are erroring as non-serializable.
class LegoSet:
def __init__(
self,
typename,
id,
productCode,
name,
slug,
primaryImage,
baseImgUrl,
overrideUrl,
variant,
):
self.__typename = typename
self.__id = id
self.__productCode = productCode
self.__name = name
self.__slug = slug
self.__primaryImage = primaryImage
self.__baseImgUrl = baseImgUrl
self.__overrideUrl = overrideUrl
self.__variant = variant
class LegoSetVariant:
def __init__(self, id, sku, salePercentage, attributes, price, listPrice):
self.__id = id
self.__sku = sku
self.__salePercentage = salePercentage
self.__atributes = attributes
self.__price = price
self.__listPrice = listPrice
class LegoSetVariantAttributes:
def __init__(
self,
rating,
maxOrderQuantity,
availabilityStatus,
availabilityText,
vipAvailabilityStatus,
vipAvailabilityText,
canAddToBag,
canAddToWishlist,
vipCanAddToBag,
onSale,
isNew,
featuredFlags,
):
self.__rating = rating
self.__maxOrderQuantity = maxOrderQuantity
self.__availabilityStatus = availabilityStatus
self.__availabilityText = availabilityText
self.__vipAvailabilityStatus = vipAvailabilityStatus
self.__vipAvailabilityText = vipAvailabilityText
self.__canAddToBag = canAddToBag
self.__canAddToWishlist = canAddToWishlist
self.__vipCanAddToBag = vipCanAddToBag
self.__onSale = onSale
self.__isNew = isNew
self.__featuredFlags = featuredFlags
class LegoSetVariantAttributesFeaturedFlags:
def __init__(self, key, label):
self.__key = key
self.__label = label
class LegoSetVariantPrice:
def __init__(self, formattedAmount, centAmount, currencyCode, formattedValue):
self.__formattedAmount = formattedAmount
self.__centAmount = centAmount
self.__currencyCode = currencyCode
self.__formattedValue = formattedValue
class LegoSetVariantListPrice:
def __init__(self, formattedAmount, centAmount):
self.__formattedAmount = formattedAmount
self.__centAmount = centAmount
Try this:
def unpack_into_dict(object):
res = {}
for key, val in object.__dict__.items():
if hasattr(val, '__dict__'):
res[key] = unpack_into_dict(val)
else:
res[key] = val
return res

Access object class Python in List

I have a question about accessing the object class from the list in python, I have compared my cases to the questions that were on stack overflow but that didn't work. I present the problem as follows
Class Booking has the properties start_date, end_date
from datetime import *
class Booking:
def __init__(self):
self.year = int(input("Enter the Year: "))
self.month = int(input("Enter the Month: "))
self.day = int(input("Enter the Day: "))
self.start_date = datetime.now()
self.end_date = datetime(self.year, self.month, self.day)
Class Room is abstract class
I create a booking(list) to store the object of the Booking class which is initialized when the Room class is initialized.
from abc import *
from booking import Booking
class Room(ABC):
bookings = []
def __init__(self, price, capacity):
self.booking = Booking()
self.price = price
self.capacity = capacity
self.bookings.append(self.booking)
#abstractmethod
def is_booked(self, start_date, end_date):
pass
SingleBed inherits Room(ABC) with price = 150 and capachity =2
from room import Room
class Singlebed(Room):
def __init__(self):
super(Singlebed, self).__init__(150, 2)
def is_booked(self, start_date, end_date):
if start_date >= end_date:
print("EndDate must be greater than StartDate")
is_Booked = False
for check_booking in self.bookings:
is_Booked = check_booking... (I wants to access objects.end_date in class Booking is saved in bookings)
single1 = Singlebed()
single2 = Singlebed()
single3 = Singlebed()
single4 = Singlebed()
single5 = Singlebed()
My question: How do I access object.end_date which is initialized with single1, single2, ...
You are iterating over your self.bookings so "check_booking" is your Booking instance and contains the attribute start_date, end_date, year, month, day
def is_booked(self, start_date, end_date):
if start_date >= end_date:
print("EndDate must be greater than StartDate")
is_Booked = False
for check_booking in self.bookings:
is_Booked = check_booking.start_date

Categories