I'm having trouble getting this function to work. The purpose of it is to delete items from a list.
def sell(inventory_list):
print()
count = int(input('How many items would you like to sell? '))
print()
for count in range(count):
print()
type = input('Enter the type of item you wish to sell? ')
print()
name = input('Enter the name of the item you wish to sell? ')
print()
price = float(input('What is the price of the item you wish to sell? $'))
items = Plant.SubPlant(type, name, price)
inventory_list.remove(items)
return inventory_list
Your inventory list doesn't have the new instance you are trying to remove. Just because it contains the same atrrs/values does not mean they are the same.
To be able to do this perhaps implement method __eq__ in your SubPlant class:
class SubPlant(object):
def __init__(self, type, name, price):
self.type = type
self.name = name
self.price = price
def __eq__(self, other):
return self.__dict__ == other.__dict__
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 am looking to create a (very!) basic inventory management system
This is the brief:
Product Inventory Project - Create an application which manages an
inventory of products. Create a product class which has a price, id,
and quantity on hand. Then create an inventory class which keeps
track of various products and can sum up the inventory value.
Here is my code so far:
class Product:
def __init__(self, id_num, price, quantity):
self.price = price
self.id_num = id_num
self.quantity = quantity
class Inventory:
def __init__(self):
self.product_list = []
def add_item(self):
id_num = int(input('Enter id: '))
price = int(input('Enter price: '))
quantity = int(input('Enter quantity: '))
self.product_list.append(Product(id_num, price, quantity))
I don't understand how to make an instance of the product class append to the product list in testing. I feel like I am way off. Any help would be much appreciated!
The code is fine. You just need to execute :)
Look at this sample I just modified inputs and made static values for fast execution:
class Product:
def __init__(self, id_num, price, quantity):
self.price = price
self.id_num = id_num
self.quantity = quantity
class Inventory:
def __init__(self):
self.product_list = []
def add_item(self):
id_num = 1 #int(input('Enter id: '))
price = 100 #int(input('Enter price: '))
quantity = 4 #int(input('Enter quantity: '))
self.product_list.append(Product(id_num, price, quantity))
inv = Inventory()
inv.add_item()
print(inv.product_list[0].price)
You should get the print result of 100 which is the price of the item
I need to create a class Person (in Python) that implements the comparison operator such as < to compare their names.
I need to ask the user for input of 10 names and generate 10 Person objects. I need to determine the first and last person among them and print them. I got the class, operator and ask for user input. All is working but I am not sure how to determine the first and last person? Any help would be appreciated, below is my code:
class Person():
def __init__(self, name):
self.name = name
def __str__(self):
return '{}'.format(self.name)
def __eq__(self, other):
return self.name == other.name
def __lt__(self, other):
return self.name < other.name
#create empty list to hold person object
persons =[]
for p in range(0,10):
if p==0:
name = input("please enter name: ")
else:
name = input("please enter another name: ")
#take user input and create 10 person object
persons.append(Person(name))
for person in persons:
print(person)
If you implement the comparison operators, you can use max and min to find the greatest and smallest Person objects.
persons = [Person('Bob'), Person('Charlie'), Person('Dee'), Person('Alice')]
print(min(persons).name) # Alice
print(max(persons).name) # Dee
I have created employee details using class by giving pre defined inputs. I'm not able to store the results into a dict. I need to write it as a csv. I would be thankful if you could help me, as I'm a novice in python
Here are my codes:
Is it correct way to use for loop in classes?
class Employee():
def main(self,name,idno,position,salary):
self.name=name
self.idno=idno
self.position=position
self.salary = salary
def input(self):
n=int(raw_input("Enter the number of employees:"))
for i in range(n):
self.name=raw_input("Name:")
self.idno=raw_input("Idno:")
self.position=raw_input("position:")
self.salary=raw_input("salary:")
print("Name:", self.name, "Idno:", self.idno, "position:", self.position,
"salary:", self.salary)
if __name__=='__main__':
result=Employee()
result.input()
First of all, I don't think you're class will be working like you intend it to. Since you're constantly overwriting the class variables, there is no point in entering more than one employee, as the class can currently only save information on one employee. I would consider saveing employees as dictionarys and have those dictionaries saved as a list in your Employee(s) class.
class Employees():
all_employees = [{...}, {...}]
dict_keys = ["name", "idno", "position",...]
def input(self):
counter = 0
n = input("Number of employees: ")
while counter < n:
new_employee = dict()
for key in dict_keys:
new_employee[key] = raw_input("{}: ".format(key))
all_employees.append(new_employee)
if __name__ == "__main__":
e = Employees()
e.input()
This illustrates what I was saying in my comment about using a for loop outside of the class:
class Employee(object):
def __init__(self, name, idno, position, salary):
self.name=name
self.idno=idno
self.position=position
self.salary = salary
def print_data(self):
print("Name:", self.name, "Idno:", self.idno, "position:", self.position,
"salary:", self.salary)
if __name__=='__main__':
def input_employee_data():
print('Enter data for an employee')
name = raw_input("Name:")
idno = raw_input("Idno:")
position = raw_input("position:")
salary = raw_input("salary:")
print('')
return name, idno, position, salary
employees = list()
n = int(raw_input("Enter the number of employees:"))
for i in range(n):
name, idno, position, salary = input_employee_data()
employee = Employee(name, idno, position, salary)
employees.append(employee)
print('List of employess')
for employee in employees:
employee.print_data()