Class in python instances - python

class fase1():
def __init__ (self, num, date, desc)
self.num = num
self.date = date
self.desc = desc
class fase2(fase1):
def __init__(self, ele):
self.ele = [ele,[]]
def __str__(self):
return self.ele
def addfase2(self, num, date, desc):
newfase = fase1()
self.ele[1].append(newfase)
namefase2 = "FASE"
cload = fase2
cload.ele = namefase2
cload.addfase2(10,"date","Desc")
when print ...
['FASE',[<__main__.fase1 instance at 0x01C2BEB8>]]
can anyone help me please?

you have an array containing your fase1 object, which isn't initialized in your addfase2 method (as you'd probably want)
def addfase2(self, num, date, desc):
newfase = fase1(num, date, desc)
also if you add a __str__ method to fase1, you won't see anymore the object repr
def __str__(self):
return self.desc + ' ' + self.num + ' ' + self.date
or something like that

Related

(Python Derived Classes) Not getting the correct output

This is my desired output:
Name: Smith, Age: 20, ID: 9999
Here is my code so far
class PersonData:
def __init__(self):
self.last_name = ''
self.age_years = 0
def set_name(self, user_name):
self.last_name = user_name
def set_age(self, num_years):
self.age_years = num_years
# Other parts omitted
def print_all(self):
output_str = 'Name: ' + self.last_name + ', Age: ' + str(self.age_years)
return output_str
class StudentData(PersonData):
def __init__(self):
PersonData.__init__(self) # Call base class constructor
self.id_num = 0
def set_id(self, student_id):
self.id_num = student_id
def get_id(self):
return self.id_num
course_student = StudentData()
course_student = StudentData()
course_student.get_id(9999)
course_student.set_age(20)
course_student.set_name("Smith")
print('%s, ID: %s' % (course_student.print_all(), course_student.get_id()))
At the moment, it isn't running. I would really appreciate it if someone could help out. It is returning a type error for line 34, and I am not sure how to correct it. Any help would be greatly appreciated.
You're invoking the parent init wrongly there...
Here's how you're supposed to do it:
class PersonData:
def __init__(self):
self.last_name = ''
self.age_years = 0
def set_name(self, user_name):
self.last_name = user_name
def set_age(self, num_years):
self.age_years = num_years
# Other parts omitted
def print_all(self):
output_str = 'Name: ' + self.last_name + ', Age: ' + str(self.age_years)
return output_str
class StudentData(PersonData):
def __init__(self):
super().__init__() # Call base class constructor
self.id_num = 0
def set_id(self, student_id):
self.id_num = student_id
def get_id(self):
return self.id_num
course_student = StudentData()
course_student = StudentData()
course_student.set_id(9999)
course_student.set_age(20)
course_student.set_name("Smith")
print('%s, ID: %s' % (course_student.print_all(), course_student.get_id()))
I also noticed that in the execution, you were calling course_student.get_id(9999) but I think you meant course_student.set_id(9999)

Product Inventory program that takes products with an ID, quantity, and price and uses an Inventory class to keep track of the products

The Product class seems to work fine but I'm trying to figure out how to get the Inventory class to separate each product into there specific categories. I feel like I'm close but whenever I try and print out the inventory it just shows where it's stored in memory and doesn't actually print anything out. The output i receive when running is at the bottom. I want it to print out the actual products and data, not the instance of it stored in memory.
class Product:
def __init__(self, pid, price, quantity):
self.pid = pid
self.price = price
self.quantity = quantity
def __str__(self):
#Return the strinf representing the product
return "Product ID: {}\t Price: {}\t Quantity: {}\n".format(self.pid, self.price, self.quantity)
def get_id(self):
#returns id
return self.pid
def get_price(self):
#returns price
return self.price
def get_quantity(self):
#returns quantity
return self.quantity
def increase_quantity(self):
self.quantity += 1
def decrease_quantity(self):
self.quantity -= 1
def get_value(self):
value = self.quantity * self.price
return 'value is {}'.format(value)
product_1 = Product('fishing', 20, 10)
product_2 = Product('apparel', 35, 20)
class Inventory:
def __init__(self, products):
self.products = products
self.fishing_list = []
self.apparel_list = []
self.value = 0
def __repr__(self):
return "Inventory(products: {}, fishing_list: {}, apparel_list: {}, value: {})".format(self.products, self.fishing_list, self.apparel_list, self.value)
def add_fishing(self):
for product in self.products:
if product.get_id() == 'fishing':
self.fishing_list.append(product)
return '{} is in the fishing section'.format(self.fishing_list)
def add_apparel(self):
for product in self.products:
if product.get_id() == 'apparel':
self.apparel_list.append(product)
return '{} is in the apparel section'.format(self.apparel_list)
inventory_1 = Inventory([product_1, product_2])
inventory_1.add_fishing()
print(inventory_1)
OUTPUT = Inventory(products: [<main.Product instance at 0x10dbc8248>, <main.Product instance at 0x10dbc8290>], fishing_list: [<main.Product instance at 0x10dbc8248>], apparel_list: [], value: 0)
You need to specify how an object of the class Inventory should be printed.
To do this you need to implement at least one of the following functions in your class.
__repr__
__str__
This answer helps, which of both you should use: https://stackoverflow.com/a/2626364/8411228
An implementation could look something like this:
class Inventory:
# your code ...
def __repr__(self):
return str(self.products) + str(self.fishing_list) + str(self.apparel_list) + str(self.value)
# or even better with formatting
def __repr__(self):
return f"Inventory(products: {self.products}, fishing_list: {self.fishing_list}, apparel_list: {self.apparel_list}, value: {self.value})
Note that I used in the second example f strings, to format the output string.

TypeError: __str__ returned non-string (type NoneType)

So for my last assingment in my python course at uni, I have to write a program consisting of three objects, two of which inherit. I keep running into a snag especially with regards to the last two objects. Here is my code:
class Course:
def __init__(self,title="",ID=0):
self._ID = ID
self._title = title
def getID(self):
return self._ID
def getTitle(self):
return self._title
def setTitle(self,title):
self._title = title
def setID(self,ID):
self._ID = ID
def __repr__(self):
return "Title: " + self._title + "ID: " + str(self._ID)
class OfferedCourse(Course):
def __init__(self,title="",ID=0,enrollment=[]):
super().__init__(title,ID)
self._enrollment = len(enrollment)
def getEnrollment(self):
return self._enrollment
def addStudent(self,stu):
if stu in enrollment:
print("Student is already enrolled.")
else:
enrollment.append(stu)
def dropStudent(self,stu):
if stu in enrollment:
def __repr__(self):
super().__repr__() + "Enrollment: " + str(self._enrollment)
class StudentCourse(Course):
def __init__(self,grade,ID=0,title=""):
super().__init__(title,ID)
self._grade = grade
def getGrade(self):
return self._grade
def setGrade(self,grade):
self._grade = grade
def __repr__(self):
super().__repr__() + "Grade: " + str(self._grade)
def main():
#Set primary course
lego=Course("Lego Design",32013)
#display course
print(lego)
#Set OfferedCourse
bonk=OfferedCourse("Matoran History",82932,["Josh","Rick","Greg","Chris"])
#Display OfferedCourse
print(bonk)
#Set StudentCourse
lp=StudentCourse("History of Nu-Metal",57859,82)
#display Student Course
print(lp)
At around line 60 I recieve the error:
TypeError: str returned non-string (type NoneType)
I'm pretty lost as to what is going on.
Your __repr__s don't explicitly return anything. You build up a string, then throw it away, causing None to be implicitly returned instead.
Just add a return:
def __repr__(self):
return super().__repr__() + "Grade: " + str(self._grade)
Adjustments to the source code of the original question:
add missing statement at def dropStudent(self,stu):
add missing return expression for def __repr__(self):
adjust signature of StudentCourse(Course) init to def __init__(self,title,ID,grade): to be in line with parent classes and process given statement StudentCourse("History of Nu-Metal",57859,82) as expected
add missing indentions for def main():
class Course:
def __init__(self,title="",ID=0):
self._ID = ID
self._title = title
def getID(self):
return self._ID
def getTitle(self):
return self._title
def setTitle(self,title):
self._title = title
def setID(self,ID):
self._ID = ID
def __repr__(self):
return "Title: " + self._title + "ID: " + str(self._ID)
class OfferedCourse(Course):
def __init__(self,title="",ID=0,enrollment=[]):
super().__init__(title,ID)
self._enrollment = len(enrollment)
def getEnrollment(self):
return self._enrollment
def addStudent(self,stu):
if stu in enrollment:
print("Student is already enrolled.")
else:
enrollment.append(stu)
def dropStudent(self,stu):
if stu in enrollment:
print("#todo Something is missing here...")
def __repr__(self):
return super().__repr__() + "Enrollment: " + str(self._enrollment)
class StudentCourse(Course):
def __init__(self,title,ID,grade):
super().__init__(title,ID)
self._grade = grade
def getGrade(self):
return self._grade
def setGrade(self,grade):
self._grade = grade
def __repr__(self):
return super().__repr__() + "Grade: " + str(self._grade)
def main():
#Set primary course
lego=Course("Lego Design",32013)
#display course
print(lego)
#Set OfferedCourse
bonk=OfferedCourse("Matoran History",82932,["Josh","Rick","Greg","Chris"])
#Display OfferedCourse
print(bonk)
#Set StudentCourse
lp=StudentCourse("History of Nu-Metal",57859,82)
#display Student Course
print(lp)
main()

How do I sent up a print method for my class?

Me very very new programmer, I'm new to classes and not sure how to set up a print method for this class. How do I go about setting up a print method for my class here? Thanks for anything!
class travelItem :
def __init__(self, itemID, itemName, itemCount) :
self.id = itemID
self.name = itemName
self.itemCount = itemCount
self.transactions = []
def getID(self) :
return(self, id)
def getName(self) :
return(self.name)
def setName(self, newName) :
self.name = newName
def getAvailableStart(self):
return(self.AvailableStart)
def appendTransaction(self, num) :
self.transactions.append(num)
def getTransactions(self) :
return(self.transactions)
def getReservations(self) :
Additions = 0
for num in self.transactions :
if (num > 0) :
Additions = Additions + num
return(Additions)
def getCancellations(self) :
Subtractions = 0
for num in self.transactions :
if (num < 0) :
Subtractions = Subtractions + num
return(Subtractions)
def getAvailableEnd(self) :
total = self.AvailableStart
for num in self.transactions :
total = total + num
return(total)
Remember that a method is called on an instance of a class, so if you mean to create a true method that just prints a class you can write something like
class Foo(object):
def print_me(self):
print(self)
foo_instance= Foo()
foo_instance.print_me()
But it sounds like you want to customize the output of print(). That is what the built in method __str__ is for, so try this.
class Foo(object):
def __str__(self):
# remember to coerce everything returned to a string please!
return str(self.some_attribute_of_this_foo_instance)
a good example from your code might be
...
def __str__(self):
return self.getName + ' with id number: ' + str(self.getId) + 'has ' + str(self.getTransactions) + ' transactions'
You must use a __str__ special method:
class travelItem:
...
def __str__(self):
return "a string that describe the data I want printed when print(instance of class) is called"

How to refer to an object's own container

I'm working on getting better with OOP in Python and I've run into some real hackishness in one program I'm writing. It works, but it's a mess.
Below is a short test example to illustrate. It creates cars of either 0, 2, or 4 windows into a list, and then compares the first element with the rest of the list.
The 3rd method of the first class shows what I'm worried about. I just want to be able to refer to whatever container that particular object is in without having to call it from the parameters each time. It isn't even that bad in this example, but what I'm working on has it in so many places that it's starting to get confusing.
import random
class Car:
def __init__ (self, company, doors, id):
self.company = company
self.doors = doors
self.id = id
def printDoors(self, id):
print 'Car ' + `self.id` + ' has ' + `self.doors` + ' doors.'
def findSameDoors(self, id):
# these next lines are the ones that really bother me
companyAbstract = self.company + 's'
for i in eval(companyAbstract):
if self.id != i.id and self.doors == i.doors:
print 'Car ' + `i.id` + ' does too!'
class Company:
def __init__ (self, types):
self.types = types
def typesToNum(self):
result = []
for i in self.types:
if i == 'sedan':
result.append(4)
elif i == 'convertible':
result.append(2)
else:
result.append(0)
return result
porsche = Company(['sedan', 'convertible'])
honda = Company(['sedan', 'convertible', 'motorcycle'])
porsches = []
for i in range(10):
porsches.append(Car('porsche', random.choice(porsche.typesToNum()), i))
hondas = []
for i in range(10):
hondas.append(Car('honda', random.choice(honda.typesToNum()), i))
porsches[0].printDoors(0)
porsches[0].findSameDoors(0)
Just in case it matters, Python 2.4.3 on RHEL. Thanks!
If I'm understanding your question right, you want to attach the list of cars to the company object:
import random
class Car:
def __init__ (self, company, doors, id):
self.company = company
self.doors = doors
self.id = id
def printDoors(self, id):
print 'Car ' + `self.id` + ' has ' + `self.doors` + ' doors.'
def findSameDoors(self, id):
for i in self.company.cars:
if self.id != i.id and self.doors == i.doors:
print 'Car ' + `i.id` + ' does too!'
class Company:
def __init__ (self, types):
self.types = types
self.cars = []
def typesToNum(self):
result = []
for i in self.types:
if i == 'sedan':
result.append(4)
elif i == 'convertible':
result.append(2)
else:
result.append(0)
return result
porsche = Company(['sedan', 'convertible'])
honda = Company(['sedan', 'convertible', 'motorcycle'])
for i in range(10):
porsche.cars.append(Car(porsche, random.choice(porsche.typesToNum()), i))
for i in range(10):
honda.cars.append(Car(honda, random.choice(honda.typesToNum()), i))
porsche.cars[0].printDoors(0)
porsche.cars[0].findSameDoors(0)
There's more cleanup that could be done to it, but I think that should solve your immediate concern.

Categories

Resources