How to make an inventory program execute - python

I'm still learning python. I am trying to write a program that develops a car inventory. I am creating an automobile class that will be used by a dealership as a vehicle inventory program. The following attributes should be present in your automobile class:
private string make
private string model
private string color
private int year
private int mileage
How can I make this execute and give prompts for input. It's not doing it.
class Automobile():
__make = ""
__model = ""
__color = ""
__year = 0
__mileage = 0
def __init__(self, make = None, model = None, color = None, year = None, mileage = None):
self.make = make
self.model = model
self.color = color
self.year = year
self.mileage = mileage
def add_vehicle(self):
auto = Automobile()
vehicle_file = open('vehicle.txt', 'a')
make = input("Enter make: ")
model = input("Enter model: ")
color = input("Enter color: ")
year = input("Enter year: ")
mileage = input("Enter mileage: ")
vehicles = Automobile(make, model, color, year, mileage)
vehicle_list = [vehicles.make, vehicles.model, vehicles.color, vehicles.year, vehicles.mileage]
for item in vehicle_list:
vehicle_file.write("%s\t" % item)
vehicle_file.write("\n")
vehicle_file.close()
print("Your record has been succesfully added to the inventory")
def delete_vehicle(self):
del_rec = input("Enter record to delete: ")
with open("vehicle.txt","r+") as f:
new_f = f.readlines()
f.seek(0)
for line in new_f:
if del_rec not in line:
f.write(line)
f.truncate()
print("Succesfully deleted record from inventory")
def set_make(self, make):
self.make = make
def get_make(self):
return self.make
def set_model(self, model):
self.model = model
def get_model(self):
return self.model
def set_color(self, color):
self.color = color
def get_color(self):
return self.color
def set_year(self, year):
self.year = year
def get_year(self):
return self.year
def set_mileage(self, mileage):
self.mileage = mileage
def get_mileage(self):
return self.mileage

Related

__init__() missing 7 required positional arguments

I want to Inheritance my animal class to Dog class.Everything is good until ı want to write Dog.add_info() at operation 1.I wrote Dog = Dog(animal) at line 46 but ı think there are a problem but ı can't find out what it is.I learning 'class' thing and 'Inheritance' thing first.
import random
class animal():
def __init__(self,name,legs,place,move,weight,lenght):
self.name = name
self.legs = legs
self.place = place
self.move = move
self.weight = weight
self.lenght = lenght
def __str__(self):
return "Name: {}\nLegs: {}\nPlace: {}\nMove: {}\nWeight: {}\nLenght: {}".format(self,self.name,self.legs,self.place,self.move,self.weight,self.lenght)
def add_info(self):
info_name = input("Enter name")
info_legs = input("Enter how many legs this animal have")
info_place = input("Enter where this animal live")
info_move = input("Enter how move this animal")
info_weight = input("Enter Weight")
info_lenght =input("Enter lenght")
self.name = info_name
self.legs = info_legs
self.place = info_place
self.move = info_move
self.weight = info_weight
self.lenght = info_lenght
class Dog(animal):
def __init__(self,name,legs,place,move,weight,lenght,feather,aggresivity):
super().__init__(self,name,legs,place,move,weight,lenght)
self.feather = feather
self.aggresivity = aggresivity
def __str__(self):
return "Name: {}\nLegs: {}\nPlace: {}\nMove: {}\nWeight: {}\nLenght: {}\nFeather: {}\nAggresivity {}".format(self, self.name, self.legs,self.place, self.move,self.weight, self.lenght,self.feather,self.aggresivity)
def add_info(self):
super().add_info()
info_feather = input("Enter are your dog have feather or not 'have' or 'haven't")
info_aggresivity =input("Enter are your dog aggresive or passive")
self.feather = info_feather
self.aggresivity = info_aggresivity
def pick_random(self):
list_dog = ["Labrador","Bulldog","Retriever,","Poodle","Beagle","Husky"]
random_dog = random.choice(list_dog)
print("Your dog is :",random_dog)
Dog = Dog(animal)
print("""
1 for add info to your dog
2 for get infos your dog have
3 for pick random dog type
q for quit
""")
choice = input("Enter operation: ")
while True:
if (choice =="q"):
print("BYE...")
break
elif(choice == "1"):
Dog.add_info()
elif(choice =="2"):
pass
elif(choice =="3"):
pass
else:
print("İnvalid operation")
Dog expects all the same arguments as animal; you are passing the class animal itself as a single argument.
Rather than duplicating all the arguments from Animal.__init__, though, use keyword arguments to simplify the definition of Dog.__init__.
First, we'll clean up Animal a little. Note that you were passing self unnecessarily to a lot of methods, as super() already captures the value to pass.
class Animal:
def __init__(self, *, name, legs, place, move, weight, length, **kwargs):
super().__init__(**kwargs)
self.name = name
self.legs = legs
self.place = place
self.move = move
self.weight = weight
self.length = length
def __str__(self):
return "Name: {}\nLegs: {}\nPlace: {}\nMove: {}\nWeight: {}\nLength: {}".format(self.name, self.legs, self.place, self.move, self.weight, self.length)
def add_info(self):
info_name = input("Enter name")
info_legs = input("Enter how many legs this animal have")
info_place = input("Enter where this animal live")
info_move = input("Enter how move this animal")
info_weight = input("Enter Weight")
info_length = input("Enter length")
self.name = info_name
self.legs = info_legs
self.place = info_place
self.move = info_move
self.weight = info_weight
self.length = info_length
Now we define Dog with only the extra arguments; anything intended for the superclass methods will be passed as arbitrary keyword arguments that Dog will pass on.
class Dog(Animal):
def __init__(self, *, feather, aggresivity, **kwargs):
super().__init__(**kwargs)
self.feather = feather
self.aggresivity = aggresivity
def __str__(self):
x = super().__str__()
return x + "\nFeather: {}\nAggresivity {}".format(self.feather, self.aggresivity)
def add_info(self):
super().add_info()
info_feather = input("Enter are your dog have feather or not 'have' or 'haven't")
info_aggresivity =input("Enter are your dog aggresive or passive")
self.feather = info_feather
self.aggresivity = info_aggresivity
def pick_random(self):
list_dog = ["Labrador","Bulldog","Retriever,","Poodle","Beagle","Husky"]
random_dog = random.choice(list_dog)
print("Your dog is :",random_dog)
Finally, we instantiate Dog using keyword arguments.
d = Dog(name="...", legs="...", ...) # etc
When initializing a class, you must provide all of the arguments required by the init method. See this great (and similarly themed) answer which illustrates the right way to initialize a instance:
class Dog:
def __init__(self, legs, colour):
self.legs = legs
self.colour = colour
fido = Dog(4, "brown")
spot = Dog(3, "mostly yellow")
In your case, you need to provide all of the required arguments: name, legs, place, move, weight, length, feather, aggresivity.
If you'd like to write a function which helps a user instantiate an instance, you could create a classmethod:
class Animal:
...
#classmethod
def add_info(cls):
info_name = input("Enter name")
info_legs = input("Enter how many legs this animal have")
info_place = input("Enter where this animal live")
info_move = input("Enter how move this animal")
info_weight = input("Enter Weight")
info_lenght =input("Enter lenght")
return cls(
info_name,
info_legs,
info_place,
info_move,
info_weight,
info_lenght
)
now, calling Animal.add_info() will prompt the user for the correct attributes and then return a properly instantiated object.
This answer is based on the information in my comments above:
import random
class animal():
def __init__(self,name,legs,place,move,weight,length):
self.name = name
self.legs = legs
self.place = place
self.move = move
self.weight = weight
self.length = length
def __str__(self):
return "Name: {}\nLegs: {}\nPlace: {}\nMove: {}\nWeight: {}\nlength: {}".format(self,self.name,self.legs,self.place,self.move,self.weight,self.length)
def add_info(self):
info_name = input("Enter name")
info_legs = input("Enter how many legs this animal have")
info_place = input("Enter where this animal live")
info_move = input("Enter how move this animal")
info_weight = input("Enter Weight")
info_length =input("Enter length")
self.name = info_name
self.legs = info_legs
self.place = info_place
self.move = info_move
self.weight = info_weight
self.length = info_length
class Dog(animal):
def __init__(self, name="sparky", legs=4, place="right here", move=True, \
weight="45 pounds", length="30 inches", feather=False, aggresivity="friendly"):
super().__init__(name, legs, place ,move, weight, length)
self.feather = feather
self.aggresivity = aggresivity
def __str__(self):
return "Name: {}\nLegs: {}\nPlace: {}\nMove: {}\nWeight: {}\nlength: {}\nFeather: {}\nAggresivity {}".format(self, self.name, self.legs,self.place, self.move,self.weight, self.length,self.feather,self.aggresivity)
def add_info(self):
super().add_info()
info_feather = input("Enter are your dog have feather or not 'have' or 'haven't")
info_aggresivity =input("Enter are your dog aggresive or passive")
self.feather = info_feather
self.aggresivity = info_aggresivity
def pick_random(self):
list_dog = ["Labrador","Bulldog","Retriever,","Poodle","Beagle","Husky"]
random_dog = random.choice(list_dog)
print("Your dog is :",random_dog)
Dog = Dog()
print("""
1 for add info to your dog
2 for get infos your dog have
3 for pick random dog type
q for quit
""")
while True:
choice = input("Enter operation: ")
if (choice =="q"):
print("BYE...")
break
elif(choice == "1"):
Dog.add_info()
elif(choice =="2"):
pass
elif(choice =="3"):
pass
else:
print("İnvalid operation")

My function menu.displayHomeMenu(m) is stuck in an infinite loop. Why?

In the code below, I want the menu to display and prompt the user for a selection. Based on the selection, I want to move on to the following if statements which allow the user to define the attributes of their vehicle. The code worked before I put the menu in a function, but this format is required for my assignment. No errors. It simply prompts for a selection over and over again. Any suggestions?
class Menu:
""" Create a Menu """
def __init__(self):
self.selection = selection
def displayHomeMenu(self):
if 2 == vehicleCount:
print("----Press 1 for car ")
print("----Press 2 for pickup ")
selection = input("----Press 3 to quit ")
return selection
else:
print("----Press 1 for car ")
selection = input("----Press 2 for pickup ")
return selection
class Vehicle:
""" Model a vehicle"""
def __init__(self, make = " ", model = "n/a", color = "n/a ", fuelType = "n/a ", *options):
""" Initialize vehicle attributes """
self.make = make
self.model = model
self.color = color
self.fuelType = fuelType
self.options = {"power windows", "powerlocks", "remote start", "backup camera", "bluetooth", "cruise control", "heated seats", "heated steering wheel"}
def getMake(self):
self.make = input("Please enter your make ")
return self.make
def getModel(self):
self.model = input("Please enter your model ")
return self.model
def getColor(self):
self.color = input("Please enter the color ")
return self.color
def getFuelType(self):
self.fuelType = input("Please enter your fuel type ")
return self.fuelType
def getOptions(self):
print("Please select from the following options: ")
input(self.options)
return self.options
class Car(Vehicle):
"""Represents a car"""
def __init__(self, make = "n/a ", model = "n/a", color = "n/a ", fuelType = "n/a "):
super().__init__(make, model, color, fuelType)
""" Initialize car attributes"""
self.engineSize = " "
self.numDoors = " "
def getEngineSize(self):
self.engineSize = input("Please enter your engine size ")
return self.engineSize
def getNumDoors(self):
self.numDoors = input("How many doors do you have ")
return self.numDoors
class pickup(Vehicle):
"""Represents a pickup"""
def __init__(self, make = " ", model = " ", color = " ", fuelType = " "):
super().__init__(make, model, color, fuelType)
""" Initialize pickup attributes """
self.cabStyle = " "
self.bedLength = " "
def getCabStyle(self):
self.cabStyle = input("Please enter your cab style ")
def getBedLength(self):
self.bedLength = input("Please enter the length of your bed ")
i = 0
list = []
vehicleCount = 0
carCount = 0
pickupCount = 0
selection = 0
while True:
vehicleCount = pickupCount + carCount
m = Menu()
Menu.displayHomeMenu(m)
if selection == "1":
# Processing for item found
c = Car(Vehicle)
Vehicle.getMake(c)
Vehicle.getModel(c)
Vehicle.getColor(c)
Vehicle.getFuelType(c)
Car.getEngineSize(c)
Car.getNumDoors(c)
newcar = vars(c)
list.append(newcar)
if carCount < 1:
carCount = carCount + 1
else:
pass
elif selection == "2":
# Processing for item not found
p = pickup(Vehicle)
Vehicle.getMake(p)
Vehicle.getModel(p)
Vehicle.getColor(p)
Vehicle.getFuelType(p)
pickup.getCabStyle(p)
pickup.getBedLength(p)
newpickup = vars(p)
list.append(newpickup)
if pickupCount < 1:
pickupCount = pickupCount + 1
else:
for i in list:
print(i)
You are not using the return value from displayHomeMenu():
while True:
vehicleCount = pickupCount + carCount
m = Menu()
selection = m.displayHomeMenu() # Assign the return value to selection
if selection == "1":
# Processing for item found
c = Car(Vehicle)
Vehicle.getMake(c)
Vehicle.getModel(c)
Vehicle.getColor(c)
Vehicle.getFuelType(c)
Car.getEngineSize(c)
Car.getNumDoors(c)
newcar = vars(c)
list.append(newcar)
if carCount < 1:
carCount = carCount + 1
else:
pass
elif selection == "2":
# Processing for item not found
p = pickup(Vehicle)
Vehicle.getMake(p)
Vehicle.getModel(p)
Vehicle.getColor(p)
Vehicle.getFuelType(p)
pickup.getCabStyle(p)
pickup.getBedLength(p)
newpickup = vars(p)
list.append(newpickup)
if pickupCount < 1:
pickupCount = pickupCount + 1
else:
for i in list:
print(i)

class method TypeError "Int object not callable"

TypeError: 'int' object is not callable
class Car():
def __init__(self, make, model, year):
"""initialize attribuites to describe a car"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
self.increment_odometer = 0
def update_odometer(self, mileage):
"""
Set the odometer reading to the given value.
Reject the change if it attempts to roll the odometer back.
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You cannot roll back the odometer.")
def read_odometer(self):
"""print at statement which shows the car's miles"""
print("This car has " + str(self.odometer_reading) + " " + "miles on it.")
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def increment_odometer(self, miles):
"""Add the given amount to the odometer reading."""
self.odometer_reading += miles
my_old_car = Car ('subaru', 'outback', 2013)
print (my_old_car.get_descriptive_name())
my_old_car.update_odometer(23500)
my_old_car.read_odometer()
my_old_car.increment_odometer(100)
my_old_car.read_odometer()
Output:
2013 Subaru Outback
This car has 23500 miles on it.
Traceback (most recent call last):
File "cars.py", line 42, in <module>
my_old_car.increment_odometer(100)
TypeError: 'int' object is not callable
As mentioned you define a name for an increment_odometer object in the __init__ and later define a method with the same name. Just remove the self.increment_odometer = 0 in the __init__
class Car():
def __init__(self, make, model, year):
"""initialize attribuites to describe a car"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
# self.increment_odometer = 0 ----> remove this line
def update_odometer(self, mileage):
"""
Set the odometer reading to the given value.
Reject the change if it attempts to roll the odometer back.
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You cannot roll back the odometer.")
def read_odometer(self):
"""print at statement which shows the car's miles"""
print("This car has " + str(self.odometer_reading) + " " + "miles on it.")
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def increment_odometer(self, miles):
"""Add the given amount to the odometer reading."""
self.odometer_reading += miles
my_old_car = Car ('subaru', 'outback', 2013)
print (my_old_car.get_descriptive_name())
my_old_car.update_odometer(23500)
my_old_car.read_odometer()
my_old_car.increment_odometer(100)
my_old_car.read_odometer()

How do I change a superClass attribute that's inside of a subClass?

When I define the __init__ of ProductionWorker, I also need to set the attributes of EmployeeClass. I entered "Bob" and "001121" as a test and it works but I need to be able to change it in my main from the input of the user.
class ProductionWorker(EmployeeClass):
SHIFT = {1: "day shift", 2: "night shift"}
def __init__(self, shift=None, hourly_pay=None):
EmployeeClass.__init__(self, "Bob", "001121")
self.__shift = shift
self.set_shift = shift
self.__hourly_pay = hourly_pay
self.set_hourly_pay = hourly_pay
# setters
def set_shift(self, shift):
if shift in ProductionWorker.SHIFT:
self.__shift = shift
else:
self.__shift = None
def set_hourly_pay(self, hourly_pay):
self.__hourly_pay = hourly_pay
# getters
def get_shift(self):
return self.__shift
def get_hourly_pay(self):
return self.__hourly_pay
def __str__(self):
summary = EmployeeClass.__str__(self)
return summary + "They work on the " + ProductionWorker.SHIFT[self.__shift] + " and make " + "$" \
+ str(format(self.__hourly_pay, "0.2f")) + " an hour."
My main:
from Employee import EmployeeClass
from Employee import ProductionWorker
e_name = input("Enter the name of the employee: ")
e_number = input("Enter the ID number of the employee: ")
e_shift = int(input("Enter 1 if they work day shift or 2 if they work night shift: "))
e_hourly_pay = float(input("Enter how much they make hourly (numerical): "))
x = EmployeeClass(e_name, e_number)
z = ProductionWorker(e_shift, e_hourly_pay)
print(z)
This is the result I get:
Enter the name of the employee: Joe
Enter the ID number of the employee: 5555
Enter 1 if they work day shift or 2 if they work night shift: 2
Enter how much they make hourly (numerical): 30
The employee's name is Bob. Bob's ID number is: 001121. They work on the night shift and make $30.00 an hour.
You have to use arguments as any with any other parameters:
class ProductionWorker(EmployeeClass):
SHIFT = {1: "day shift", 2: "night shift"}
def __init__(self, name, number, shift=None, hourly_pay=None):
EmployeeClass.__init__(self, name, number)
self._shift = shift
self.hourly_pay = hourly_pay
#property
def shift(self):
return self._shift
#shift.setter
def shift(self, shift):
if shift in ProductionWorker.SHIFT:
self._shift = shift
else:
self._shift = None
def __str__(self):
summary = EmployeeClass.__str__(self)
return summary + "They work on the {} and make ${:.2f} an hour.".format(
ProductionWorker.SHIFT[self.shift], self.hourly_pay)
name = input("Enter the name of the employee: ")
number = input("Enter the ID number of the employee: ")
shift = int(input("Enter 1 if they work day shift or 2 if they work night shift: "))
hourly_pay = float(input("Enter how much they make hourly (numerical): "))
z = ProductionWorker(name, number, shift, hourly_pay)
print(z)
I would include the parameters of the EmployeeClass in the init method parameters of the ProductionWorker to pass along to the superclass.
For python 3 you can do super().__init___() rather than EmployeeClass.__init__().
Additionally you should consider using descriptors rather than implementing getters and setters as that is the pythonic way to do that.
class ProductionWorker(EmployeeClass):
def __init__(self, name, number, shift=None, hourly_pay=None):
super().__init__(name, number)
self.__shift = shift
self.__hourly_pay = hourly_pay

TypeError: __init__() takes 1 positional argument but 4 were given

class voting():
number = 0
name = ""
surfer = ""
def __init__(self, num, na, surf):
self.number = num
self.name = na
self.surfer = surf
def save_surfer(self):
file = open("Surfer_list.txt", "a")
file.write("%07s%16s%16s\n" % (self.number, self.name, self.surfer))
file.close()
class judge():
def __init__(voting):
voting.__init__(self, num, na, surf)
def save(self):
file = open("Surfer_list.txt", "a")
file.write("%07s%16s%16s\n" % (self.number * 11, self.name, self.surfer))
file.close()
surf = ["Jonny Johns", "Juan Martino", "Joseph Smith", "Stacey O'Neill"]
num = [1, 2, 3, 4]
running = True
while running:
option = 1
for choice in surf:
print(str(option) + ". " + choice)
option = option + 1
print(str(option) + ". Giveup")
choice = int(input("Choose a surfer(1~4): "))
if choice == option:
running = False
else:
na = input("Your Name: ")
if input("Are you a Judge?(Y/N) ") == "Y":
judge(num[choice-1], na, surf[choice-1]).save()
else:
voting(num[choice-1]. na, surf[choice-1]).save()
I read this hundreds of times and I just can't find what is wrong...
I am really new to this please help me know whats wrong
I saw similar questions but those were different from mine..
I really appreciate your help
If I got it well, you want the class judge to inherit from the class voting. To specify this you should do it like this :
class voting():
number = 0
name = ""
surfer = ""
def __init__(self, num, na, surf):
self.number = num
self.name = na
self.surfer = surf
def save_surfer(self):
file = open("Surfer_list.txt", "a")
file.write("%07s%16s%16s\n" % (self.number, self.name, self.surfer))
file.close()
class judge(voting):
def __init__(self, num, na, surf):
voting.__init__(self, num, na, surf)
def save(self):
file = open("Surfer_list.txt", "a")
file.write("%07s%16s%16s\n" % (self.number * 11, self.name, self.surfer))
file.close()
Doc about inheritance in python

Categories

Resources