Let's say I have a class named Books that has the variables: author, title, and book_id. And then I have another class name Patrons that has the variables: name, patron_id, and borroweds.Borroweds is supposed to be a list of Books currently "checked out" so I would have to encorporate the class Books into the class Patron. But how would I go about doing that?
This is what I have so far:
class Book:
author= ""
title = ""
book_id= ""
# the class constructor
def __init__(self, author, title, book_id):
self.title = title
self.author = author
self.book_id = book_id
def __str__(self):
s = str("Books("+str(self.author)+", "+str(self.title)+", "+str(self.book_id+")"))
return s
def __repr__(self):
return str(self)
class Patron:
name= ""
patron_id= ""
borroweds= list()
# the class constructor
def __init__(self, name, patron_id, borroweds):
self.name= name
self.patron_id= patron_id
self.borroweds= borroweds
def __str__(self):
s= str("Patron("+str(self.name)+","+str(self.patron_id)+","+list(self.borroweds)+")")
return s
def __repr__(self):
return str(self)
borroweds = [Book('Author Authorsson', 'The book of books', 'ISBN76576575757')]
patron = Patron('thename', 'theid', borroweds)
>>> patron
Patron(thename,theid,[Books(Author Authorsson, The book of books, ISBN76576575757)])
>>> patron.borroweds[0]
Books(Author Authorsson, The book of books, ISBN76576575757)
Also, skip the class attributes, you don't need them.
class Book:
# the class constructor
def __init__(self, author, title, book_id):
self.title = title
self.author = author
self.book_id = book_id
def __str__(self):
s = str("Books("+str(self.author)+", "+str(self.title)+", "+str(self.book_id+")"))
return s
def __repr__(self):
return str(self)
class Patron:
# the class constructor
def __init__(self, name, patron_id, borroweds):
self.name= name
self.patron_id= patron_id
self.borroweds= borroweds
def __str__(self):
s= str("Patron("+str(self.name)+","+str(self.patron_id)+","+str(self.borroweds)+")")
return s
def __repr__(self):
return str(self)
Did you notice the typo in the __str__ method of Books? Your parenthesis at the end needs moved left, after self.book_id.
You don't need the class attributes because they are for "global" purposes for every 'Patron'. So if you wanted to keep track of how many patrons you make, you could update that "global" variable each time you make one, like this:
class Patron:
patron_id= 0
# the class constructor
def __init__(self, name, borroweds):
self.name= name
self.patron_id=self.patron_id
self.borroweds= borroweds
Every time you create a Patron object you could add one to the class attribute:
p1 = Patron('Dave',[Book('Me','Something', '8675309')])
print p1.patron_id
Patron.patron_id+=1
p2 = Patron('Dave',[Book('You','Others', 'Number9')])
print p2.patron_id
You'll notice the class attribute was changed and set the objects attribute. You could even create a class attribute in Patron that was a list of every Patron object and add each one during the __init__ method if you wanted. Its going to keep track of it for the class.
Also, I think you need ","+list(self.borroweds)+")" to be ","+str(self.borroweds)+")"
Related
sorry but I just started learning python not too long ago and I'm stuck in thisprogram code, I just can't get it to work like it should.
class Dog():
def __init__(self,name,breed,owner):
self.name = name
self.breed = breed
self.owner = owner
class Person():
def __init__(self,name):
self.name = name
mick = Person("Mick Jagger")
dog = Dog("Stanley","French Bulldog",mick)
print(dog.owner)
I want to get the dog's owner name but all I get is this:
= RESTART: C:/Coding Practice/Object Oriented Programming.py =
<__main__.Person object at 0x000002C5DFB02050>
Help would be appreciated.
You can use __str__ or __repr__ to get all the object's attributes in a more human-readable format.
__str__ (read as "dunder (double-underscore) string") and __repr__ (read as "dunder-repper" (for "representation")) are both special methods that return strings based on the state of the object.
class Dog():
def __init__(self,name,breed,owner):
self.name = name
self.breed = breed
self.owner = owner
def __str__(self):
return str(self.__class__) + '\n'+ '\n'.join(('{} = {}'.format(item, self.__dict__[item]) for item in self.__dict__))
class Person():
def __init__(self,name):
self.name = name
def __str__(self):
return str(self.__class__) + '\n'+ '\n'.join(('{} = {}'.format(item, self.__dict__[item]) for item in self.__dict__))
mick = Person("Mick Jagger")
dog = Dog("Stanley","French Bulldog", mick)
print(dog.owner)
str
If you print an object, or pass it to format, str.format, or str, then
if a str method is defined, that method will be called, otherwise,
repr will be used.
repr
The repr method is called by the builtin function repr and is what
is echoed on your python shell when it evaluates an expression that
returns an object.
when you assign self.owner = owner self.owner stores the reference of owner object you should access the name value by mentioning the attribute self.owner = owner.name.
class Dog():
def __init__(self,name,breed,owner):
self.name = name
self.breed = breed
self.owner_name = owner.name
class Person():
def __init__(self,name):
self.name = name
mick = Person("Mick Jagger")
dog = Dog("Stanley","French Bulldog",mick)
print(dog.owner_name)
You should add __repr__ and __str__ methods to the Person class. Or just __repr__.
class Person:
def __init__(self,name):
self.name=name
def __repr__(self)
return str(self.name)
I want to format an attribute-string of a class with another attribute of the same class like this:
class Test:
def __init__(self):
self.name = None
self.full_name = 'name, {}'.format(self.name)
def print_name(self):
print(self.full_name)
my_object = Test()
my_object.name = 'my_object'
my_object.print_name()
Now it should print 'name, my_object'
But it prints 'name, None'
What to do that the string formats with the assigned value of the object?
You need to add full_name as a property so that you can add some more logic to it:
class Test:
def __init__(self):
self.name = None
#property
def full_name(self):
return f'name, {self.name}'
def print_name(self):
print(self.full_name)
my_object = Test()
my_object.name = 'my_object'
my_object.print_name()
Resources:
property function (built-in)
I have this class and method:
class Person(object):
def __init__(self, name):
self.name = personname
self.surname = personsurname
def changenameorsurname(self, x, y):
self.x = y
return
AdamSmith = Person ("Adam", "Smith")
I want to use method changenameorsurname to change AdamSmith's name or surname, but if I use this code I'm getting a NameError"
AdamSmith.changenameorsurname(personname, Dave)
Result:
NameError: name personname is not defined.
Is there elegant way to reference personname in code like this? Or do I have to make two separate methods like this?
def changename(self, y):
self.name = y
return
AdamSmith.changename(Dave)
There are a couple of problems. Your init method needs to be fixed so you can properly construct a Person object. You can have your changenameorsurname() method take one argument that is a name and a second argument that determines whether that name is the first name or the surname. Here, I have set the default to first name.
class Person:
def __init__(self, first_name, surname):
self.first_name = first_name
self.surname = surname
def changenameorsurname(self, name, first = True):
if first:
self.first_name = name
else:
self.surname = name
def __str__(self):
return f'{self.first_name} {self.surname}'
some_guy = Person ("Adam", "Smith")
print(some_guy) #Adam Smith
some_guy.changenameorsurname("Michael")
print(some_guy) #Michael Smith
some_guy.changenameorsurname("Jones", first=False)
print(some_guy) #Michael Jones
Noob here.
Actually want to understand the concept behind returning an instance of a class within the class itself. Code snippet below don't actually work, but want to understand idea behind code in the get_student() method (more especially the last two lines).
import database
class Student(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
def save(self):
"""Save student data to database"""
pass
#staticmethod
def get_student(std_id):
"""Retrieve student from database"""
query = "query" + std_id
student = database.Database.get_one(query)
return Student(name=student['name'], gender=student['gender'])
I have been struggling with an example code that I use to practice and learn Python. Understanding the below's code is not hard, however, if I go line by line I am not sure what the following one does.
course_running.add_student(self)
How is it possible that we run add_student method of CourseRunning class to a parameter course_running (Student class, enrol method)?
I would be very grateful if you can provide an explanation how that line of code works?
The full code is provided below.
class Student:
def __init__(self, name, student_number):
self.name = name
self.student_number = student_number
self.classes = []
def enrol(self, course_running):
self.classes.append(course_running)
course_running.add_student(self)
class Department:
def __init__(self, name, department_code):
self.name = name
self.department_code = department_code
self.courses = {}
def add_course(self, description, course_code, credits):
self.courses[course_code] = Course(description, course_code, credits, self)
return self.courses[course_code]
class Course:
def __init__(self, description, course_code, credits, department):
self.description = description
self.course_code = course_code
self.credits = credits
self.department = department
self.department.add_course(self)
self.runnings = []
def add_running(self, year):
self.runnings.append(CourseRunning(self, year))
return self.runnings[-1]
class CourseRunning:
def __init__(self, course, year):
self.course = course
self.year = year
self.students = []
def add_student(self, student):
self.students.append(student)
Thanks in advance!
Igor
A CourseRunning object has its list of attending students, and a Student object has a list of courses the student is currently taking.
Say there are student1 and running_course1. We wish to enroll student1 to running_course1. We than run:
student1.enroll(running_course1)
The enroll method does two things:
self.classes.append(course_running) - which translated to `student1.classes.append(running_course1). So now the course is registered in the student's list.
course_running.add_student(self) - which translates to running_course1.add_student(student1). This invokes running_course1.add_student(self, student1) which adds the student to the course's list.
I believe this is not a full code because no any object is present no method call..
i am providing you a code please run this in your pc.
class Student:
def __init__(self, name, student_number):
self.name = name
self.student_number = student_number
self.classes = []
def enrol(self, course_running):
print "In enroll method"
self.classes.append(course_running)
course_running.add_student(self)
class Department:
def __init__(self, name, department_code):
self.name = name
self.department_code = department_code
self.courses = {}
def add_course(self, description, course_code, credits):
self.courses[course_code] = Course(description, course_code, credits, self)
return self.courses[course_code]
class Course:
def __init__(self, description, course_code, credits, department):
self.description = description
self.course_code = course_code
self.credits = credits
self.department = department
self.department.add_course(self)
self.runnings = []
def add_running(self, year):
self.runnings.append(CourseRunning(self, year))
return self.runnings[-1]
class CourseRunning:
def __init__(self, course, year):
self.course = course
self.year = year
self.students = []
def add_student(self, student):
print "student-->", student
print "In Add Student"
self.students.append(student)
course_running = CourseRunning('b.tech', '2011')
obj = Student('student_xyz', "1234")
obj.enrol(course_running)
what happening here is we are creating an object of "CourseRunning" class.
and when we call "enroll" method of "Student" class we are passing the object of "CourseRunning" class so we are able to access the method of "CourseRunning" class because "course_running" is a object of "CourseRunning" class so it will access all methods of "CourseRunning" class