def cinput():
temp = []
print ("Input name: ")
temp.append(input())
print ("Input about: ")
temp.append(input())
return temp
class Person:
def __init__(self,Name,About):
self.Name = Name
self.About = About
new_friend = Person(cinput())
how to make this code work?without changes in class Person
You can use unpacking:
new_friend = Person(*cinput())
This is roughly equivalent to
temp_input = cinput()
new_friend = Person(temp_input[0], temp_input[1])
That is, * "unpacks" the list (or iterables) and seperately use each element as an argument.
Related
I have a class I've imported into a Python file. But my code is printing the location of the object not the data stored in the object. It is giving me this output, '<Chapter_10_Program_Exercise_5.RetailItem object at 0x10e281520>' which I think is the location but how can I change that? Here's the code and a picture of the python terminal output.
class RetailItem:
# __init__ method initializes the attributes.
def __init__(self, description, units, price):
self.__item_description = description
self.__units_in_inventory = units
self.__price = price
# The set_item_description method gets the item type.
def set_item_description(self, description):
self.__item_description = description
# The set_units_in_inventory method gets number of items available.
def set_units_in_inventory(self, units):
self.__units_in_inventory = units
# The set_price method gets the cost of item.
def set_price(self, price):
self.__price = price
# The get_item_description method returns the item type.
def get_item_description(self):
return self.__item_description
# The get_units_in_inventory returns the number of items available.
def get_units_in_inventory(self):
return self.__units_in_inventory
# The get_price method returns the cost of item.
def get_price(self):
return self.__price
from Chapter_10_Program_Exercise_5 import RetailItem
class CashRegister:
# The __init__ method initializes the attributes.
def __init__(self):
self.__items = []
def clear(self):
self.__items = []
def purchase_item(self, retail_item):
self.__items.append(retail_item)
print('The item was added to the cash register.')
def get_total(self):
total_cost = 0.0
# for loop
for item in self.__items:
total_cost = total_cost +item.get_price()
return total_cost
def display_items(self):
print('The items in the cash register are:')
for item in self.__items:
print(item)
PANTS = 1
SHIRT = 2
DRESS = 3
SOCKS = 4
SWEATER = 5
def main():
pants = RetailItem('Pants', 10, 19.99)
shirt = RetailItem('Shirt', 15, 12.50)
dress = RetailItem('Dress', 3, 79.00)
socks = RetailItem('Socks', 50, 1.00)
sweater = RetailItem('Sweater', 5, 49.99)
sale_items = {PANTS:pants, SHIRT:shirt, DRESS:dress, SOCKS:socks, SWEATER:sweater}
register = CashRegister()
checkout = 'N'
while checkout =='N':
# Call the get_user_option and it is assigned to the user_option
user_option = get_user_option()
# Sale_items of argument user_option is assigned to the item
item= sale_items[user_option]
# If condition to check the items in the items_in_inventory
if item.get_units_in_inventory()== 0:
print('The item is out of stock.')
else:
register.purchase_item(item)
# New item is updated and it is assigned to the new_item
new_item = RetailItem(item.get_item_description(),
item.get_units_in_inventory()-1,
item.get_price())
# Item is updated according to the user selected option
sale_items[user_option] = new_item
# The user input is assigned to the attribute checkout
checkout = input('Are you ready to check out (Y/N)? ')
print()
print('Your purchase total is:',\
format(register.get_total(),'.2f'))
print()
register.display_items()
register.clear()
# Define the get_user_option() method to print the menu items
def get_user_option():
print('Menu')
print('-------------------')
print('1. Pants')
print('2. Shirt')
print('3. Dress')
print('4. Socks')
print('5. Sweater')
print()
option = int(input('Enter the menu number of the item you would like to purchase: '))
print()
while option > SWEATER or option < PANTS:
option = int(input('Please enter a valid item number: '))
return option
main()
Python Terminal Output
This is how python manages the printing of objects. If you want to print attributes you need to tell python which representation you want for your object.
You can do that by implementing these methods in the object class:
class RetailItem:
.
.
.
def __repr__(self):
return "RetailItem()"
def __str__(self):
return "" + self.__item_description + str(self.__units_in_inventory) + str(self.__price)
Note that the two methods will be automatically called in different situations:
>>> ri = RetailItem()
>>> ri
RetailItem()
>>> print(ri)
description 2.0 13.99
Since all variables within RetailItem are private, you'd
need to use the getter method (get_*()) to grab the info.
So to apply that to your display_items() method:
def display_items(self):
print('The items in the cash register are:')
for item in self.__items:
print("Description: %s, Units in Inventory: %d, Price: %0.2f" %
(item.get_item_description(),
item.get_units_in_inventory(),
item.get_price())
I have a class (Student) with different attributes, such as studentId, address, and courses. My str method for the class returns all the information that the user put in. However, for the attributes that are lists, such as courses, the location of the information is printed out instead of the actual information. Here is the code (sorry it's a little long, there's a bunch of classes):
class Person:
__name = None
__age = None
__address = None
def __init__(self, name, age=0, address=None):
self.set_name(name)
self.set_age(age)
self.set_address(address)
def __str__(self):
return 'Name: ' + self.__name + '\n' + \
'Age: ' + str(self.__age) + '\n' + \
'Address: ' + str(self.__address)
def set_name(self, name):
self.__name = name
def get_name(self):
return self.__name
def set_age(self, age):
self.__age = age
def get_age(self):
return self.__age
def set_address(self, address):
self.__address = address
def get_address(self):
return self.__address
class Student(Person):
def __init__(self, name, studentID= None, age= 0, address= None):
super(Student, self).__init__(name, age, address)
self.set_studentID(studentID)
self.__courses =[]
def __str__(self):
result = Person.__str__(self)
result += '\nStudent ID:' + self.get_studentID()
for item in self.__courses:
result += '\n ' + str(item)
return result
def set_studentID(self, studentID):
if isinstance(studentID, str) and len(studentID.strip()) > 0:
self.__studentID = studentID.strip()
else:
self.__studentID = 'NA'
def get_studentID(self):
return self.__studentID
def add_course(self, course):
print('in add_course')
self.__courses.append(course)
def get_courses(self):
for i in range(len(self.__courses)):
return self.__courses[i]
class Course:
__courseName = None
__dept = None
__credits = None
def __init__(self, courseName, dept= 'GE', credits= None):
self.set_courseName(courseName)
self.set_dept(dept)
self.set_credits(credits)
def __str__(self):
return self.get_courseName() + '/' + self.get_dept() + '/' + str(self.get_credits())
def set_courseName(self, courseName):
if isinstance(courseName, str) and len(courseName.strip()) > 0:
self.__courseName = courseName.strip()
else:
print('ERROR: Name must be a non-empty string')
raise TypeError('Name must be a non-empty string')
def get_courseName(self):
return self.__courseName
def set_dept(self, dept):
if isinstance(dept, str) and len(dept.strip()) > 0:
self.__dept = dept.strip()
else:
self.__dept = "GE"
def get_dept(self):
return self.__dept
def set_credits(self, credits):
if isinstance(credits, int) and credits > 0:
self.__credits = credits
else:
self.__credits = 3
def get_credits(self):
return self.__credits
students = []
def recordStudentEntry():
name = input('What is your name? ')
age = input('How old are you? ')
studentID= input('What is your student ID? ')
address = input('What is your address? ')
s1 = Student(name, studentID, int(age), address)
students.append(s1)
s1.add_course(recordCourseEntry())
print('\ndisplaying students...')
displayStudents()
print()
def recordCourseEntry():
courses = []
for i in range(2):
courseName = input('What is the name of one course you are taking? ')
dept = input('What department is your course in? ')
credits = input('How many credits is this course? ')
c1 = Course(courseName, dept, credits)
print(c1)
courses.append(c1)
displayCourses(courses)
return courses
def displayCourses(courses):
print('\ndisplaying courses of student... ')
for c in range(len(courses)):
print(courses[c])
def displayStudents():
for s in range(len(students)):
print()
print(students[s])
recordStudentEntry()
This is how the code above prints out the 'displaying students...' part:
displaying students...
Name: sam
Age: 33
Address: 123 st
Student ID:123abc
[<__main__.Course object at 0x000002BE36E0F7F0>, <__main__.Course object at
0x000002BE36E0F040>]
I know that it is printing out the location because I need to index into the list. However, the length of the list will be different every time. Normally if I wanted to index into a list, for example, to print a list of names, I would do:
listOfNames = ['sam', 'john', 'sara']
for i in range(len(listOfNames)):
print(listOfNames[i])
or
listOfNames = ['sam', 'john', 'sara']
for i in listOfNames:
print(i)
(not sure what if any difference there is between the 2 ways since they both print out the same way:)
sam
john
sara
How can I write something like the indexing into a list technique shown here in my str method for my class so that it prints the information and not the location?
It would be good to keep to the standard conventions for Python, such as naming
private attributes for objects with single underscores, not double underscores.
The latter are reserved for Python "internal" attributes and methods.
Also, it is convention to use object attributes for objects with get/set methods,
not class attributes. This will make it easier to inspect your objects, while
still maintaining data hiding. Example:
class Course:
def __init__(self, courseName, dept= 'GE', credits= None):
self._courseName = None
self._dept = None
self._credits = None
self.set_courseName(courseName)
...
Your question about why the courses don't print out the way you expected
is rooted in a programming error with the way you programmed the recording
of courses. In recordCourseEntry(), you record two courses and put them
in a list. However, you pass that to your Student object using a method
intended for one course at a time. My suggested fix would be:
...
# s1.add_course(recordCourseEntry())
courses = recordCourseEntry()
for course in courses:
s1.add_course(course)
...
This will probably be enough to get you going. An example output I got was:
Name: Virtual Scooter
Age: 33
Address: 101 University St.
Student ID:2021
ff/GE/3
gg/GE/3
I'm writing a text adventure game and I'm trying to take an input for an object in a room, search for it in the objects list, then take that object and append it to the inventory (inv) list. I need to search for the object using the the input of its' name, which is one of the attributes.
class room():
def __init__(self, name):
self.objects = []
class player(room):
def __init__(self, name, inv):
self.name = name
self.inv = []
class things(room):
def __init__(self, name, is_weapon):
self.name = name
self.weapon = is_weapon
currentRoom = center
objLen = len(currentRoom.objects)
if currentRoom.objects:
for x in range(len(currentRoom.objects)):
print("Objects here: ",currentRoom.objects[x].name)
pickUp = input("Would you like to take any objects: ")
for a in range(0,objLen):
if pickUp.upper() == currentRoom.objects.name:
ind = currentRoom.objects.index(pickUp.upper().name)
Andy.inv.append(currentRoom.objects[ind])
currentRoom.objects.pop[ind]
else:
print("Object not found in this room!")
Got it.
for a in range(0,objLen):
if pickUp.upper() == currentRoom.objects[a].name:
Player.inv.append(currentRoom.objects[a])
currentRoom.objects.pop(a)
So I am still a beginner programmer who has been tasked with sorting objects created by a csv file with the attributes lname, fname, gender, age (in that order) and sort them by the lname attribute. I have achieved this, however I now need to delete one of the objects (I chose a random one to test) and this is what I have so far:
class FitClinic:
def __init__(self, lname, fname, gender, age):
self.lname = lname
self.fname = fname
self.gender = gender
self.age = int(age)
def __del__(self):
print("Customer has been deleted")
def get_lname(self):
return self.lname
def get_fname(self):
return self.fname
def get_gender(self):
return self.gender
def get_age(self):
return self.age
fh=open('fit_clinic_20.csv', 'r')
fh.seek(3)
listofcustomers=[]
for row in fh:
c = row.split(",")
listofcustomers.append(FitClinic(c[0], c[1], c[2], c[3]))
sorted_list=sorted(listofcustomers,key=lambda x: x.get_lname())
for x in sorted_list:
if x.get_lname()==("Appleton"):
del x
print(x.get_lname(),x.get_fname(),x.get_gender(),x.get_age())
now it obviously doesnt work and I need some help.
del x just deletes the temporary variable x, it has no effect on the list. You need to use del listofcustomers[pos], but first you have to find the position in the list.
try:
pos = next(i for i,v in enumerate(listofcustomers) if v.get_lname() == "Appleton")
del listofcustomers[pos]
except StopIteration:
pass // Ignore if not found
See Python: return the index of the first element of a list which makes a passed function true for numerous ways to find the index of an element that matches a criteria.
You can remove an item from a list with list comprehension:
sorted_list[:] = [x for x in sorted_list if not(x.get_lname()==("Appleton"))]
A working example:
class FitClinic:
def __init__(self, lname):
self.lname = lname
def __del__(self):
print("Customer has been deleted")
def get_lname(self):
return self.lname
# Create example
sorted_list = [FitClinic('a'), FitClinic('b'), FitClinic('c'), FitClinic('Appleton')]
sorted_list[:] = [x for x in sorted_list if not(x.get_lname()=="Appleton")]
Now sorted_list is.
a
b
c
This example is better with filter since it removes all clinics where lname is Appleton:
sorted_list = list(filter(lambda c: c.get_lname() != "Appleton", sorted_list))
If you want to remove only the first one, use Barmar's answer.
This is the same as a list comprehension, which Python is better at optimizing:
sorted_list = [c for c in sorted_list if c.get_lname() != "Appleton"]
Just Try this:
for x in sorted_list: # Loops through Customers in List
if x.get_lname() == "Appleton": # Check if the last name is Apple
sorted_list.remove(x) # Remove each from the list, Pretty self explanatory
else: # you only want to print if the last name is not APppleton
print(x.get_lname(), x.get_fname(), x.get_gender(), x.get_age())
.remove removes an object from a list so you do not need to track the index of the loop.
Read this w3schools tutorial for more list operations
I have a list of objects. I would like to check some string if that string exists as a field value any object in the list. for example,
class Ani:
name = ''
def __init__(self, name):
self.name = name
def getName(self):
return self.name
animal1 = Ani('alica')
animal2 = Ani('rex')
animal3 = Ani('bobik')
animal4 = Ani('dobik')
animal5 = Ani('sobik')
a = [animal1, animal2, animal3,animal4,animal5]
my problem to write a code in order to see if there is an object with given name. for example "chip".
You can iterate over the array of objects, and check with each object's getName function.
class Ani:
name = ''
def __init__(self, name):
self.name = name
def getName(self):
return self.name
animal1 = Ani('alica')
animal2 = Ani('rex')
animal3 = Ani('bobik')
animal4 = Ani('dobik')
animal5 = Ani('sobik')
animals = [animal1, animal2, animal3,animal4,animal5]
searched_animal = 'rex'
for animal in animals:
if animal.getName() == searched_animal:
print('Found')
break
You can use any plus a comprehension:
any(animal.getName() == "chip" for animal in animals)
Iterating a list containing anything is quite simple really. Like so:
animal_to_find = "someAnimal"
for animal in animals:
if animal.getName() == animal_to_find:
print("Found a match for: " + animal)
You can use the getName method present in Ani class for this program
class Ani:
name = ''
def __init__(self, name):
self.name = name
def getName(self):
return self.name
animal1 = Ani('alica')
animal2 = Ani('rex')
animal3 = Ani('bobik')
animal4 = Ani('dobik')
animal5 = Ani('sobik')
animals = [animal1, animal2, animal3,animal4,animal5]
key = 'chip'
flag=0
for animal in animals:
if animal.getName() == key:
print('Found')
flag=1
break
if flag==0:
print("Not Found")