getting all attributes of an object python 3 - python-3.x

I read all questions and answers about this but none seems to help , using var from one of the answers was close but i need to use the same function with different objects. What should i change in the function so i don't have to make multiple functions for each object, i mean say i have another objects Human , Plants do i have to make a function for each one just changing the animal syntax:
class Animal(object):
def __init__(self):
self.legs = 2
self.name = 'Dog'
self.color= 'Spotted'
self.smell= 'Alot'
self.age = 10
self.kids = 0
def get_info(self) :
if __name__ == '__main__':
animal = Animal()
temp = vars(animal)
for item in temp:
print(item , ' : ' , temp[item])

Instead of hard coding the variable you should do this:
class Animal(object):
def __init__(self, legs, name, color, smell, age, kids):
self.legs = legs
self.name = name
self.color= color
self.smell= smell
self.age = age
self.kids = kids
if __name__ == '__main__':
animal = Animal(2, 'Dog', 'Spotted', 'Alot', 10, 0)
temp = vars(animal)
for item in temp:
print(item , ' : ' , temp[item])

i figured it out all i had to do was assigning user input to a variable then call it from objects like this :
class Animal(object):
def __init__(self):
self.legs = 2
self.name = 'Dog'
self.color= 'Spotted'
self.smell= 'Alot'
self.age = 10
self.kids = 0
noun = input()
def get_info(noun) :
if __name__ == '__main__':
character = Object.objects[noun]
temp = vars(character)
for item in temp:
print(item , ' : ' , temp[item])

Related

How can I print the method from within a Class?

I have created two separate classes with the intent of creating instances of those Classes and accessing the methods within the Classes. However, when I run this code, I cannot print out the list of grades in the print.grades method.
'''
class Student:
def __init__(self, name, year):
self.name = name
self.year = year
self.grades = []
def add_grade(self, grade):
if type(grade) == Grade:
self.grades.append(grade)
else:
pass
def get_average(self):
sum_score = 0
for i in self.grades:
sum_score += i
ave = sum_score / len(grades)
return ave
def print_grades(self):
for i in self.grades:
print(i)
roger = Student("Roger van der Weyden", 10)
sandro = Student("Sandro Botticelli", 12)
pieter = Student("Pieter Bruegel the Elder", 8)
class Grade:
def __init__(self, score):
self.score = score
def is_passing(self, grade):
if grade >= self.minimum_passing:
return "Passing!"
else:
return "Not Passing"
minimum_passing = 65
new_Grade = Grade(100)
pieter.add_grade(new_Grade)
print(new_Grade.is_passing(100))
pieter.add_grade(90)
pieter.add_grade(100)
pieter.print_grades
'''

Is it possible to change the output so that "Arlene" and "Klusman" don't have an extra set of parenthesis around them?

I'm writing code for an assignment where I can't change the main. The way I have it written, it prints like in the screenshot below:
Here is my code:
import csv
class Customer:
def __init__(self, cust_id, name, lastName, companyName, address, city, state, cust_zip):
self.cust_id = cust_id
self.first_name = name
self.last_name = lastName
self.company_name = companyName
self.address = address
self.city = city
self.state = state
self.zip = cust_zip
def getFullName(self):
return(self.first_name, self.last_name)
def getFullAddress(self):
return(self.getFullName(), self.company_name, self.address, self.city, self.state, self.zip)
def get_customers():
myList = []
counter = 0
with open("customers.csv", "r") as csv_file:
reader = csv.reader(csv_file, delimiter = ",")
for row in reader:
if counter!=0:
customer1 = Customer(row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7])
myList.append(customer1)
counter+=1
return myList
def find_customer_by_id(customers, cust_id):
for i in range(len(customers)):
if cust_id == customers[i].cust_id:
return customers[i]
return None
def main():
#main is fully implemented with no modification expected
print("Customer Viewer")
print()
customers = get_customers()
while True:
cust_id = input("Enter customer ID: ").strip()
print()
customer = find_customer_by_id(customers, cust_id)
if customer == None:
print("No customer with that ID.")
print()
else:
print(customer.getFullAddress())
print()
again = input("Continue? (y/n): ").lower()
print()
if again != "y":
break
print("Bye!")
if __name__ == "__main__":
main()
Why are there parenthesis and, can you get rid of them?
I tried to different approaches but nothing changed the output in the intended way

How to remove an object from list by a value

My problem is that I created a list of students with name and number. The task is now to remove a student by his number. My problem is that my code doesn't work.
Another problem is that it always shows the memory address instead of the value of the object.
Thanks in advance
class Student:
def __init__(self, name, number):
self.name = name
self.number = number
from .student import Student
class Course:
def __init__(self, name, code, credit, student_limit):
self.name = name
self.code = code
self.credit = credit
self.student_limit = student_limit
students = []
def add_student(self, new_student):
self.student = new_student
self.students.append(new_student)
print("Student added" +str(self.students))
def remove_student_by_number(self, student_number):
self.student_number = student_number
if student_number in self.students: self.students.remove(student_number)
print("Student removed" + str(self.students))
from .course import Course
class Department:
def __init__(self, name, code):
self.name = name
self.code = code
courses = []
def add_course(self, course):
self.course = course
self.courses.append(course)
print("Course added" +str(self.courses))
from python import *
def main():
alice = Student("Alice", 1336)
bob = Student("Bob", 1337)
math_dept = Department("Mathematics and Applied Mathematics", "MAM")
math_course = Course("Mathematics 1000", "MAM1000W", 1, 10)
math_dept.add_course(math_course)
math_course.add_student(bob)
math_course.add_student(alice)
math_course.remove_student_by_number(alice.number)
if __name__ == "__main__":
main()
self.students is a list of Student instance so it will print the instance's memory address if the method __str__ is not implemented (see here for example). You should try to print each property like student.name or student.number explicitly.
Anyway you are trying to find student_number in list of Student so of course it will never run the remove line. Instead use if student_number in [student.number for student in self.students] which is looking up the student's number list, not the student list itself. However in this case, you also want to remove the student with the student_number as the input so you may need to use a loop like this:
def remove_student_by_number(self, student_number):
for student in self.students:
if student.number == student_number:
print("Student removed" + str(student.name))
self.students.remove(student)
break

In OOP in python, are different instances of an object when initialised with a default value the same?

I am trying to understand object oriented programming. I am doing this by creating a small poker like program. I have come across a problem whose minimal working example is this:
For this code:
import random
class superthing(object):
def __init__(self,name,listthing=[]):
self.name = name
self.listthing = listthing
def randomlyadd(self):
self.listthing.append(random.randint(1,50))
def __str__(self):
return '\nName: '+str(self.name)+'\nList: '+str(self.listthing)
Aboy = superthing('Aboy')
Aboy.randomlyadd()
print(Aboy)
Anotherboy = superthing('Anotherboy')
Anotherboy.randomlyadd()
print(Anotherboy)
I expect this output :
Name: Aboy
List: [44]
(some number between 1 and 50)
Name: Anotherboy
List: [11]
(again a random number between 1 and 50)
But what I get is:
Name: Aboy
List: [44]
(Meets my expectation)
Name: Anotherboy
List: [44,11]
(it appends this number to the list in the previous instance)
Why is this happening? The context is that two players are dealt a card from a deck. I am sorry if a similar question exists, if it does, I will read up on it if you can just point it out. New to stack overflow. Thanks in advance.
For the non minimal example, I am trying this:
import random
class Card(object):
def __init__(self, suit, value):
self.suit = suit
self.value = value
def getsuit(self):
return self.suit
def getval(self):
return self.value
def __str__(self):
if(self.suit == 'Clubs'):
suitstr = u'\u2663'
elif(self.suit == 'Diamonds'):
suitstr = u'\u2666'
elif(self.suit == 'Hearts'):
suitstr = u'\u2665'
elif(self.suit == 'Spades'):
suitstr = u'\u2660'
if((self.value<11)&(self.value>1)):
valuestr = str(self.value)
elif(self.value == 11):
valuestr = 'J'
elif(self.value == 12):
valuestr = 'Q'
elif(self.value == 13):
valuestr = 'K'
elif((self.value == 1)|(self.value == 14)):
valuestr = 'A'
return(valuestr+suitstr)
class Deck(object):
def __init__(self,DeckCards=[]):
self.DeckCards = DeckCards
def builddeck(self):
suits = ['Hearts','Diamonds','Clubs','Spades']
for suit in suits:
for i in range(13):
self.DeckCards.append(Card(suit,i+1))
def shuffle(self):
for i in range(len(self)):
r = random.randint(0,len(self)-1)
self.DeckCards[i],self.DeckCards[r] = self.DeckCards[r],self.DeckCards[i]
def draw(self):
return self.DeckCards.pop()
def __str__(self):
return str([card.__str__() for card in self.DeckCards])
def __len__(self):
return len(self.DeckCards)
class Player(object):
def __init__(self,Name,PlayerHandcards = [],Balance = 1000):
self.Name = Name
self.Hand = PlayerHandcards
self.Balance = Balance
def deal(self,deck):
self.Hand.append(deck.draw())
def __str__(self):
return 'Name :'+str(self.Name)+'\n'+'Hand: '+str([card.__str__() for card in self.Hand])+'\n'+'Balance: '+str(self.Balance)
deck1 = Deck()
deck1.builddeck()
deck1.shuffle()
Alice = Player('Alice')
Alice.deal(deck1)
print(Alice)
Bob = Player('Bob')
Bob.deal(deck1)
print(Bob)
And after dealing to Bob they both have the same hands. If you have some other suggestions regarding the code, you are welcome to share that as well.
This is a duplicate of “Least Astonishment” and the Mutable Default Argument as indicated by #Mad Physicist. Closing this question for the same.

Python get object attributes

My loop at the bottom of my code doesn't seem to print song title if I type print SongList[i] it prints the memory address for the given object. I'm sure it's returning the Song List but the object attributes. Am I missing a method? Sorry if this has already been answered in the past I cannot find an example.
class Song:
def __init__(self, title, artist, duration = 0):
self.title = title
self.artist = artist
self.duration = duration
class Album:
def __init__(self, albumTitle, releaseYear, albumSize):
self.albumTitle = albumTitle
self.releaseYear = releaseYear
self.trackList = []
self.albumSize = albumSize
def addSong(self, albumSong, position):
self.trackList.append((position, albumSong))
class Artist:
def __init__(self, name, year):
self.name = name
self.year = year
self.members = []
def addMembers(self, bandMember):
self.members.append(bandMember)
class Person:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
BlinkAndSee = Album("Blink and See", 2018, 5)
Band = Artist("Dinkers", 2002)
AlexThomas = Person("Alex Thomas", 23, "Female")
SeanJohnson = Person("Sean Johnson", 25, "Male")
SineadMcAdams = Person("Sinead McAdams", 21, "Female")
Band.members.append(AlexThomas)
Band.members.append(SeanJohnson)
Band.members.append(SineadMcAdams)
Stoner = Song("Stoner", Band, 320)
Blink = Song("Blink and See", Band, 280)
See = Song("See", Band, 291)
DumbnessAndSand = Song("Dumbness and Sand", Band, 231)
OrangeYellow = Song("Orange Yellow", Band, 353)
BlinkAndSee.trackList.append(Stoner)
BlinkAndSee.trackList.append(BlinkAndSee)
BlinkAndSee.trackList.append(See)
BlinkAndSee.trackList.append(DumbnessAndSand)
BlinkAndSee.trackList.append(OrangeYellow)
SongList = BlinkAndSee.trackList
#Loop through the Song list from album tracklist
for i in range(SongList.__len__()):
print(SongList[i].title)
This is caused by (probably) a typo:
Note how you append BlinkAndSee.trackList.append(BlinkAndSee)?
This essentially appends the object itself to the track list;
of course, this will cause an error, since an Artist does not have the attribute title that you are accessing further down when iterating over the list.
In that case, I would suggest you add some lines to your Album.addSong() function that verifies that the passed argument is of a certain type;
Something like
def addSong(self, albumSong, position):
if not isinstance(albumSong, Song):
print("Passed wrong type to addSong")
else:
self.trackList.append((position, albumSong))

Resources