Access object class Python in List - python

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

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

How to add new variables into objects to use in classes

I have the code:
import timedelta
class Tune:
def __init__(self, title, artist, duration):
self.title = title
self.artist = artist
self.duration = duration
class Play:
def __init__(self):
self.tracks = []
def add(self, song):
self.tracks.append(song)
def delete(self, number):
del (self.song(number))
def look(self, song):
for song in self.tracks:
print(f"{song.artist} - {song.title}")
def duration(self):
s=0
for y in range(0,len(self.song)):
s = s + self.song[y]
print(int(datetime.timedelta(seconds=s)))
n = int(input("Enter the number of tracks to add"))
playlist = Play()
for i in range(n):
title, artist, duration = input("Enter the title, artist, and duration of a track").split(',')
song = Tune(title, artist, duration)
playlist.add(song)
playlist.look()
playlist.duration
playlist.delete (2)
for every input, i have to make it an object pertaining to its class and add it to the list, with the option of removing it when it is called. When song.look is called, it is supposed to print out the title and artist in the list. For example, if the input is:
2
Artic Monkeys,R U Mine?,324
Artic Monkeys,Do I wanna know?,253
when the program is executed it should output:
1 - Artic Monkeys - R U Mine?
2 - Artic Monkeys - Do I wanna know?
when duration is executed:
00:09:62
when the delete is executed:
1 - Artic Monkeys - R U Mine?
and if song.duration is called, it should output the total duration in the format of hours:minutes:seconds. I think the add and look is correct, my only problem is how do i make it so that it can have track number and how can i use it to remove said tracks? and is my program for duration correct?
Edit: I can only change the def for the class Play, I cant change the contents of Tune
import time
class Tune:
def __init__(self, title, artist, duration):
self.title = title
self.artist = artist
self.duration = duration
class Play:
def __init__(self):
self.tracks = []
def add(self, song):
self.tracks.append(song)
def delete(self, number):
self.tracks.pop(number-1)
def look(self):
for i in range(len(self.tracks)):
print(f"{i+1} -{self.tracks[i].artist} - {self.tracks[i].title}")
def duration(self):
s = 0
for y in range(len(self.tracks)):
s += int(self.tracks[y].duration)
print(time.strftime('%H:%M:%S', time.gmtime(s)))
n = int(input("Enter the number of tracks to add"))
playlist = Play()
for i in range(n):
title, artist, duration = input("Enter the title, artist, and duration of a track").split(',')
song = Tune(title, artist, duration)
playlist.add(song)
playlist.look()
playlist.duration()
print("After Deleting 2nd....")
playlist.delete (2)
playlist.look()
print("After Deleting 2nd....")
playlist.delete (2)
playlist.look()

Calling variable from another class in “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)

Why does my class raise an AttributeError?

I might be blind, but I really can't see why this class fails with:
AttributeError: NextSunday instance has no attribute 'trigger'
from datetime import datetime
from datetime import time
from datetime import timedelta
class NextSunday():
def __init__(self, trigger=None):
"""
Get date of, and number of days until, next Sunday.
Arguments:
- `trigger`: Add an extra week if less than trigger number of days.
"""
self.str = u'%s (%s days)' % (self.date().date(), self.no_days())
self.trigger = trigger
def __unicode__(self):
return self.str
def __str__(self):
return unicode(self).encode('utf-8')
def __repr__(self):
return '<Next Sunday: ' + self.str + '>'
def no_days(self):
"""Get date of next sunday. """
days = None
for i in range(7):
dt = datetime.now() + timedelta(days=i)
if dt.weekday() == 6:
days = i
# Add another week if there are less days left then trigger
if self.trigger:
if days < self.trigger:
days += 7
return days
def date(self):
# The datetime obj contains the next sunday, but also the current time
dt_of_next_sun = datetime.now() + timedelta(days=self.no_days())
# Get the whole day
date_of_next_sun = datetime.combine(dt_of_next_sun.date(),
time(23, 59))
return date_of_next_sun
You need to switch these
self.str = u'%s (%s days)' % (self.date().date(), self.no_days())
self.trigger = trigger
like this
self.trigger = trigger
self.str = u'%s (%s days)' % (self.date().date(), self.no_days())
because otherwise the no_days method is called before the self.trigger attribute is created. This is bad because the no_days method tries to read the value of the self.trigger attribute:
if self.trigger:
if days < self.trigger:

Categories