I'm trying to understand inheritance better. In the following code, when I try to print friend.salary, it throws an AttributeError. Doesn't WorkingStudent inherit all methods of the Student class?
class Student:
def __init__(self,name,school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks)/len(self.marks)
def friend(self,friend_name):
return Student(friend_name, self.school)
anna = Student("Anna","MIT")
friend = anna.friend("Motilal")
#print (friend.name)
#print (friend.school)
class WorkingStudent(Student):
def __init__(self,name,school,salary):
super().__init__(self,name,school)
self.salary = salary
anna = WorkingStudent("Anna","SXS",25000)
anna.friend("Greg")
anna.marks.append(50)
print friend.salary
You should modify your source code as below
class Student:
def __init__(self,name,school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks)/len(self.marks)
def friend(self,friend_name):
return Student(friend_name, self.school)
anna = Student("Anna","MIT")
friend = anna.friend("Motilal")
#print (friend.name)
#print (friend.school)
class WorkingStudent(Student):
def __init__(self,name,school,salary):
super(WorkingStudent,self).__init__(name,school)
self.salary = salary
# anna = WorkingStudent("Anna","SXS",25000)
def friend(self,friend_name):
return WorkingStudent(friend_name, self.school, self.salary)
# You should put your code here, because as your original code
# anna is an instance of Student not WorkingStudent class
# so it and its friend don't have "salary".
anna = WorkingStudent("Anna","SXS",25000) # After this line, anna is a different variable to "anna" variable that was defined before (anna = Student("Anna","MIT"))
friend = anna.friend("Greg") # friend now is an instance of WorkingStudent class, so it have salary
anna.marks.append(50)
print(friend.salary)
Editted. So code can work now
Related
I am generating a class of persons and want to get information about a certain person by input. I would like to use the str funtction because I am trying to understand it better. My Idea goes as follows:
class Person:
__init__(self, f_name, l_name):
self.f_name = f_name
self.l_name = l_name
__str__(self):
return "The persons full name is:" + f_name + l_name
person1 = Person(Peter, Punk)
person2 = Person(Mia, Munch)
person = input("What persons full name would you like to know?")
print(person) #I am aware that this just fills in the string saved in person, but how do I connect it to the variable?
another idea was to do it as follows:
#class stays the same except:
__init__(self, f_name, l_name):
self.f_name = f_name
self.l_name = l_name
list.append(self)
#and then for the main:
list = []
person1 = Person(Peter, Punk)
person2 = Person(Mia, Munch)
person = input("What persons full name would you like to know?")
index = list(person)
print(list[index])
Thankful for any edvice since I am obviously new to Python :D
I think OP has some concept problems here which this answer may go some way to help with.
Start by building a robust class definition. Simple in this case as there are just 2 attributes. Note the use of setters, getters and str, repr and eq dunder overrides.
A small function that checks if a given Person can be found in a list of Persons and reports accordingly.
Create a list with 2 different Person instances
Create another Person that is known not to match anything already in the list.
Run check()
Modify the 'standalone' Person to make it equivalent to something previously constructed.
Run check()
class Person:
def __init__(self, forename, surname):
self._forename = forename
self._surname = surname
#property
def forename(self):
return self._forename
#forename.setter
def forename(self, forename):
self._forename = forename
#property
def surname(self):
return self._surname
#surname.setter
def surname(self, surname):
self._surname = surname
def __str__(self):
return f'{self.forename} {self.surname}'
def __repr__(self):
return f'{self.forename=} {self.surname=}'
def __eq__(self, other):
if isinstance(other, type(self)):
return self.forename == other.forename and self.surname == other.surname
return False
def check(list_, p):
if p in list_:
print(f'Found {p}')
else:
print(f'Could not find {p}')
plist = [Person('Pete', 'Piper'), Person('Joe', 'Jones')]
person = Person('Pete', 'Jones')
check(plist, person)
person.surname = 'Piper'
check(plist, person)
Output:
Could not find Pete Jones
Found Pete Piper
You probably want a mapping between a name and an object. This is what Python's dict dictionary structure is for:
people = {} # an empty dictionary
people[f'{person1.f_name} {person1.l_name}'] = person1
people[f'{person2.f_name} {person2.l_name}'] = person2
This is creating a string of the first and last name.
You can then lookup the Person object using the full name:
print(people['Peter Punk'])
You could do this with list comprehension like so (also allowing multiple people to have the same first name)
class Person:
__init__(self, f_name, l_name):
self.f_name = f_name
self.l_name = l_name
__str__(self):
return "The persons full name is:" + f_name + l_name
personList= []
personList.append(Person(Peter, Punk))
personList.append(Person(Mia, Munch))
personName = input("What persons full name would you like to know?")
print([str(person) for person in personList if person.f_name == personName])
so im new to programming, so for anything hahahahahah.
So im trying to create a simple manegment system by creating a person registration and a room registration, and simply place the amount of people registerd into the amount of room.
Só this is what im up-to:
class Person:
counter = 0
persons = []
def __init__ (self,name,surname):
self.name = name
self.surname = surname
self.id = Person.counter
Person.counter += 1
def createPeople(self):
print(self.name, self.surname)
def peopleCounter (self):
print(Person.counter)
def storePeople ():
a = Person.createPeople.append(Person.persons)
print(a)
person1 = Person("Jack", "Wayne")
person1.createPeople()
person2 = Person("Gabriel", "Jones")
person2.createPeople()
print(Person.counter)
print(storePeople)
If what you are trying to do is store all persons created in the class attribute persons, then this is how you can go about it:
class Person:
counter = 0
persons = []
def __init__ (self,name,surname):
self.name = name
self.surname = surname
self.id = Person.counter
Person.counter += 1
def createPeople(self):
print(self.name, self.surname)
Person.persons.append(self.name + ' '+ self.surname) #Every time this method is called, it adds the person to the persons list
def peopleCounter (self):
print(Person.counter)
person1 = Person("Jack", "Wayne")
person1.createPeople()
person2 = Person("Gabriel", "Jones")
person2.createPeople()
print(Person.counter)
print(Person.persons)
Output from my end
Jack Wayne
Gabriel Jones
2
['Jack Wayne', 'Gabriel Jones']
I had an assignment to create a python code using class to create a group with 3 members (aggregation relationship). This is my code so far:
class Member:
def __init__(self,name,age):
self.name = name
self.age = age
def getInfo(self):
memberInfo = "Name: " + str(self.name) + "." + "Age: " + str(self.age)
return memberInfo
class Group:
def __init__(self,name):
self.name = name
self.memlist = []
def addMember(self,member):
self.memlist.append(member)
def getInfo(self):
info = "Member List: \n"
for i in range(len(self.memlist)):
info += self.memlist[i].getInfo() + "\n"
print(info)
break
mem1 = Member("Chi",20)
mem2 = Member("Bach",7)
mem3 = Member("Gen", 22)
group1 = Group("Siblings")
group1.addMember(mem1)
group1.addMember(mem2)
print(group1.getInfo())
print(mem2.getInfo())
print(group1.memList)
But it has shown an error: AttributeError: 'Group' object has no attribute 'memList'. Is there anything I can do to fix this?
I wrote little function for listing members and their ages.
class member:
def __init__(self, name, age):
self.name = name
self.age = age
def member_Info(self):
memberInfo = f"Name: {str(self.name)}-->Age: {str(self.age)}"
return memberInfo
class Group:
def __init__(self, name):
self.name = name
self.memlist = []
def addMember(self, name):
self.memlist.append(name)
def getInfo(self):
for i in range(len(self.memlist)):
info = self.memlist[i].member_Info() + "\n"
print(info)
This all_members function is basically getting the information stored in the member class and return to list. I print using memlist in Group but it didn't work out so I made a new list using all_member function and get information from memlist in group1 with the code that you used for getting information in memlist at group1.getInfo .
def all_members():
all_mems = []
for i in range(len(group1.memlist)):
all_mems.append(group1.memlist[i].member_Info())
print(all_mems)
mem1 = member("Chi", "20")
mem2 = member("Bach", "7")
mem3 = member("Gen", "22")
group1 = Group("Siblings")
group1.addMember(mem1)
group1.addMember(mem2)
group1.addMember(mem3)
print(group1.getInfo())
print(mem2.member_Info() + "\n")
print(all_members())
I guess this isn't the best answer you can get but I think it will work and also I learn many things while trying to correct it so thank you for posting that.
change
print(group1.memList)
to
print(group1.memlist)
Below is a simple python 2.7 code using class and objects.
class Student:
def __init__(self,name,pref):
self.name = name
self.preference = pref
student1=Student("Tom","cce")
print(student1.name)
print(student1.preference)
How can this code be implemented so that the name and preference values(string) are taken using user-input(raw_input())
Here is also a working code.
class Student:
def __init__(self,name,pref):
self.name = name
self.preference = pref
student1=Student(raw_input("enter name:"),raw_input("enter branch:"))
print(student1.name)
print(student1.preference)
Here's an example:
class Student:
def __init__(self,name,pref):
self.name = name
self.preference = pref
name1 = raw_input("Name:")
pref1 = raw_input("Preference:")
student1 = Student(name1, pref1)
print(student1.name)
print(student1.preference)
So I have 2 files that work together using each other's classes.
I have
class Student:
"""A class to model a student with name, id and list of test grades"""
def __init__(self, name, id):
"""initializes the name and id number; sets list of grades to []"""
self.s_name = name
self.ident = id
self.tests=[]
def getID(self):
return self.ident
def get_name(self):
""" returns the student name"""
return self.s_name
def addtest(self,t):
"""adds a grade to the list of test grades """
self.tests.append(t)
def __str__(self):
"""returns the student name and the current list of grades"""
return self.s_name + " " + str(self.tests) + " "
def comp_av(self):
"""returns the average of the current set of grades or 'no grades'
if appropriate"""
if len(self.tests) > 0:
sum = 0.0
for item in self.tests:
sum = sum + item
average = float(sum)/len(self.tests)
return average
else:
return "no grades"
Which is completely done. I also have code that is from the teacher's point of view. The students are not just represented by their names but by an object of class Student. Each Student object has their name and ID number, but also a list of test scores. Right now Course has only the constructor and the __str__ method.
from LabStudentClass import *
class Course:
""" A class to model a course which contains a list of students"""
def __init__(self,teacher):
"""Sets up a class to hold and update students"""
self.students = []
self.teacher = teacher
def __str__(self):
""" prints the course by listing each student in the class"""
result = self.teacher+"'s Class\n"
for s in self.students:
name = s.get_name()
result = result + name + '\n'
return result
c = Course("Dr. Bradshaw")
#print c
def AddStudent(name, id):
student1 = Student('Mary Comtpon', '3456')
student2 = Student('Billy Jo', '2345')
student3 = Student( 'Anne lou', '1090')
print student1
print student2
print student3
My goal is to create a method AddStudent: This method gets two parameters, a student name and an ID. A new Student object is created and added to the course.
Add 3 students to your class and print out the class to test it.
However, the students aren't printing and I'm not really sure what the problem is.
Add this method to your Course class:
def addStudent(self, name, id):
student = new Student(name, id)
self.students.append(student)
Then, replace the function you wrote at the bottom with the following:
c.addStudent('Mary Comtpon', '3456')
c.addStudent('Billy Jo', '2345')
c.addStudent('Anne lou', '1090')
print c