I'm a beginner at coding and tried looking up the error but could not find why it showed up. Could someone please explain it to me?
My code as follows is:
class Automobile:
__material = None
__height = None
__width = None
__engine_size = None
def set_values(self, mat, height, width, engsz="M"):
self.__material = mat
self.__height = height
self.__width = width
self.__engine_size = engsz
def getMat(self):
return self.__material
def getHeight(self):
return self.__height
def getWidth(self):
return self.__width
def getEngineSize(self):
return self.__engine_size
class Car(Automobile):
__pricePU = None
def __findPricePerUnit(self):
return priceDict[self.getMat]
def price(self):
return self.getWidth * self.getHeight * self.__findPricePerUnit
print("A new car is being made")
print("What are the dimensions wanted for the new car in")
mat = input("Enter material: ")
height = input("Enter height: ")
width = input("Enter width: ")
car1 = Car()
car1.set_values(mat, height, width)
print("A new car has been made!")
print("The price of this new car is: ")
print(car1.price)
My input for this is:
iron=10,steel=20,gold=50,diamond=100
gold
1.5
5
The OUTPUT shown at the end is:
A new car has been made!
The price of this new car is:
<bound method Car.price of <__main__.Car object at 0x0000025DE7E84C70>>
I am not exactly sure why this is coming up, could someone please explain this to me!
There are several errors in the code, some of which are as follows:
On the last line, you should execute the price function like this car1.price()
In the price function, you should execute the functions instead of multiplying the pointers of the functions, like this:
def price(self):
return self.getWidth() * self.getHeight() * self.__findPricePerUnit()
There is no priceDict, so there will be an error in __findPricePerUnit as well.
print("A new car has been made!")
print("The price of this new car is: ")
print(car1.price())
Because price() is a method.
Related
I have just started OOPS and am completely new to it. I have a very basic question regarding the different ways I can call a function within another function in same class.
class StuffAnimal:
def __init__(self,name,color,weight,issitting):
self.name = name
self.color = color
self.weight = weight
self.issitting = issitting
self.x = 0
self.y = 0
self.situation = " "
def standup (self):
if self.issitting == True :
print("the stuff toy is sitting")
return "sit"
else :
print ("the stuff toy is not sitting")
return "notsit"
def move_teddy (self):
self.situation = standup(self.issitting)
if self.situation == 'sit' :
print ("teddy is not in the situation to move please change issitting to True")
elif self.situation == 'notsit' :
print ("teddy is in the situation to move please give cordinates")
self.x = int(input("x cordinates : "))
self.y = int(input("y cordinates : "))
print("teddy moved to ",self.x,self.y)
but when i tried to call the function I got the following error.
teddy.move_teddy()
NameError: name 'standup' is not defined
This doesn't works. Can someone explain where did I go wrong.
Thank you.
As the method definition tells the method def standup(self)
is a instance method, (because of self)
does not accept parameters (because there is only self)
So the good way to cal it is
self.situation = self.standup()
Regarding the name of your methods, I'd say standup should set issitting to False, and define a sitdown method. Then the code of move_teddy would be more logic
class StuffAnimal:
def __init__(self, name, color, weight, issitting):
self.name = name
self.color = color
self.weight = weight
self.issitting = issitting
self.x = 0
self.y = 0
def standup(self):
self.issitting = False
print("the stuff toy is now up")
def sitdown(self):
self.issitting = True
print("the stuff toy is now sit")
def move_teddy(self):
if self.issitting:
print("teddy is not in the situation to move please change issitting to True")
else:
print("teddy is in the situation to move please give cordinates")
self.x = int(input("x cordinates : "))
self.y = int(input("y cordinates : "))
print("teddy moved to ", self.x, self.y)
teddy = StuffAnimal("teddy", "black", 20, True)
teddy.move_teddy()
teddy.standup()
teddy.move_teddy()
teddy is not in the situation to move please change issitting to True
the stuff toy is now up
teddy is in the situation to move please give cordinates
x cordinates : 12
y cordinates : 34
teddy moved to 12 34
self parameter doesn't require to be called, and when you call a function from a class in the same class, your self. prefix !
class StuffAnimal:
def __init__(self,name,color,weight,issitting):
self.name = name
self.color = color
self.weight = weight
self.issitting = issitting
self.x = 0
self.y = 0
self.situation = " "
def standup (self):
if self.issitting == True :
print("the stuff toy is sitting")
return "sit"
else :
print ("the stuff toy is not sitting")
return "notsit"
def move_teddy (self):
self.situation = self.standup()
if self.situation == 'sit' :
print ("teddy is not in the situation to move please change issitting to True")
elif self.situation == 'notsit' :
print ("teddy is in the situation to move please give cordinates")
self.x = int(input("x cordinates : "))
self.y = int(input("y cordinates : "))
print("teddy moved to ",self.x,self.y)
This is the exercise:
Write the special method __str__() for CarRecord.
Sample output with input: 2009 'ABC321'
Year: 2009, VIN: ABC321
The following code is what I have came up with, but I'm receiving an error:
TYPEERROR: __str__ returned non-string
I can't figure out where I went wrong.
class CarRecord:
def __init__(self):
self.year_made = 0
self.car_vin = ''
def __str__(self):
return "Year:", (my_car.year_made), "VIN:", (my_car.car_vin)
my_car = CarRecord()
my_car.year_made = int(input())
my_car.car_vin = input()
print(my_car)
You're returning a tuple using all those commas. You should also be using self, rather than my_car, while inside the class. Try like this:
def __str__(self):
return f"Year: {self.year_made}, VIN: {self.car_vin}"
The f before the string tells Python to replace any code in braces inside the string with the result of that code.
class Car:
def __init__(self):
self.model_year = 0
self.purchase_price = 0
self.current_value = 0
def print_info():
print('Car Info') # It specifies a print_info class method but doesnt actually need to print anything useful.
def calc_current_value(self, current_year):
depreciation_rate = 0.15
car_age = current_year - self.model_year
self.current_value = round(self.purchase_price * (1 - depreciation_rate) ** car_age)
def print_info(self):
print("Car's information:")
print(" Model year:", self.model_year)
print(" Purchase price:", self.purchase_price)
print(" Current value:", self.current_value)
if __name__ == "__main__":
year = int(input())
price = int(input())
current_year = int(input())
my_car = Car()
my_car.model_year = year
my_car.purchase_price = price
my_car.calc_current_value(current_year)
my_car.print_info()
def __str__(self):
return "Year: {}, VIN: {}".format(self.year_made, self.car_vin)
The trick here is that you pull values from the top of the class as they are set later in the code.
This answer works for grading
def __str__(self):
return f"Year: {}, VIN: {}".format(self.year_made, self.car_vin)`
This is easier to understand
def __str__(self):
f"Year: {self.year_made}, VIN: {self.car_vin}")
This question already has answers here:
return, return None, and no return at all?
(5 answers)
Closed 3 years ago.
I'm trying to piece together a small assignment in Python OOP, but I'm not sure where I'm wrong.
I have two classes: Shoe and Store.
In the Shoe class I just create the Shoe, and that Store class is where I'm doing all the methods.
I'm trying to create an "add shoe" method that will check if the shoe exists in a given list, if not, it will add it. I'm checking if the shoe exists by comparing the shoeID object.
Here is my code:
class Shoe(object):
def __init__(self, shoeID, shoePrice, shoeSize, quantity):
self.shoeID = shoeID
self.shoePrice = shoePrice
self.shoeSize = shoeSize
self.quantity = quantity
def __str__(self):
return "Shoe ID:", self.shoeID, "Shoe Price:", str(self.shoePrice), "Shoe Size:", str(self.shoeSize), "Quantity:", str(self.quantity)
class Store(object):
def __init__(self):
self.shoeList = []
def __str__(self):
return "Shoe list: " + self.shoeList
def add_shoe(self, newShoe):
for i in self.shoeList:
if i.shoeID == newShoe.shoeID:
print("Shoe already exists, updating quantity")
i.quantity += newShoe.quantity
else:
print("This is a new shoe, adding it to the list")
self.shoeList.append(i)
return
This is my tester:
import shoes
testStore = shoes.Store()
shoe1 = shoes.Shoe(123, 100, 40, 2)
print(testStore.add_shoe(shoe1))
My output is always None. I tried changing a bunch of stuff but I guess I'm just missing something stupid that I don't see.
I'd love to get some help.
Thanks!
you code has a lot of issues. I fixed all
class Shoe(object):
def __init__(self, shoeID, shoePrice, shoeSize, quantity):
self.shoeID = shoeID
self.shoePrice = shoePrice
self.shoeSize = shoeSize
self.quantity = quantity
def __str__(self):
return "Shoe ID: {} Shoe Price: {} Shoe Size: {} Quantity: {}".format(self.shoeID, str(self.shoePrice),str(self.shoeSize), str(self.quantity))
class Store(object):
def __init__(self):
self.shoeDict = {}
def __str__(self):
return "Shoe list: " + "\n".join([str(i) for i in self.shoeDict.values()])
def add_shoe(self, newShoe):
if newShoe.shoeID in self.shoeDict:
print("Shoe already exists, updating quantity")
self.shoeDict[newShoe.shoeID].quantity += newShoe.quantity
else:
print("This is a new shoe, adding it to the list")
self.shoeDict[newShoe.shoeID] = newShoe
return
testStore = Store()
shoe1 = Shoe(123, 100, 40, 2)
testStore.add_shoe(shoe1)
testStore.add_shoe(Shoe(123, 100, 40, 2))
print(testStore)
This is a new shoe, adding it to the list
Shoe already exists, updating quantity
Shoe list: Shoe ID: 123 Shoe Price: 100 Shoe Size: 40 Quantity: 4
One thing that I am struggling with while trying to learn concepts of OOP is creation of class instances. Most of the tutorials online will explain basic principles like Init, Self, Inheritance etc.. but when it comes to creating instances of the class itself it is usually reduced to something like that:
emp1 = Employee("John")
emp2 = Employee("Leviticus")
In reality most of us beginners will want to create instance of a class dynamically (On press of button etc..) not directly in code and also will be interessted in keeping track of our instances. What I was able to come up is this:
from tkinter import *
import random
class Point:
_registry = []
def __init__(self, x_pos, y_pos):
self._registry.append(self)
self.x_pos = x_pos
self.y_pos = y_pos
print(self.x_pos, self.y_pos)
def create_point():
Point(random.randint(1,20),random.randint(1,20))
window = Tk()
button = Button(window, text = "Add point", command=create_point)
button.pack()
window.mainloop()
Can someone advise if this is a proper way to do this? Shouldnt the fnction create_point be within Point class? What is the proper way to keep track of instances and later delete them? Shall I use some sort of ID attribute to keep track and "itemize" my instances? Is there any good source with tutorial that deals with that?
Thank you
Jacob
after completing tutorial at: https://pythonschool.net/category/oop.html I managed to get what I wanted by doing:
class Point:
def __init__(self,ID, xcor, ycor):
self._ID = ID
self._xcor = xcor
self._ycor = ycor
def report(self):
return {"ID:":self._ID,"xcor":self._xcor,"ycor":self._ycor}
def get_ID(self):
return self._ID
class Points:
def __init__(self):
self._points = []
def add_point(self, point):
self._points.append(point)
def return_index_from_ID(self, ID):
for i, o in enumerate(self._points):
if o.get_ID() == ID:
break
return i
def delete_point(self, index):
del self._points[index]
def print_contents(self):
for x in self._points:
print(x.report())
def return_empty_ID(self):
list = []
for x in self._points:
list.append(x.get_ID())
if not list:
return 1
else:
for i in range(1, max(list)+2):
if i not in list: break
return i
def add_point( xcor, ycor, points):
points.add_point(Point(points.return_empty_ID(), xcor, ycor))
def delete_point(ID, points):
points.delete_point(ID)
Simple main function for testing to show what I was after:
from point_class import *
myPoints = Points()
noexit = True
while noexit:
print("**********************************************")
print("0 - Exit")
print("1 - Add Point")
print("2 - Print Points")
print("3 - Delete Points")
print("**********************************************")
choice = int(input("Option selected: "))
if choice == 0:
noexit = False
elif choice == 1:
add_point(3,5,myPoints)
elif choice == 2:
myPoints.print_contents()
elif choice == 3:
ID = int(input("Please insert ID of point: "))
delete_point(myPoints.return_index_from_ID(ID),myPoints)
Not sure if I made sense in the title, but I have created classes and now I need to associate a class with a number. For example 1 would be the penny (object) and with this object I have associated height and weight. I need help asking how to associate this class with the number 1.
I know i need to have it ask the question like something like so
print "Enter 1 for Penny\nEnter 5 for Nickel\nEnter 10 for Dime\nEnter 25 for Quarter\nEnter 50 for halfdollar\nEnter 100 for Dollar"
I need it to then ask me to Enter number:
Than ask how many of that coin of the number you just entered:
Than give me the total weight
Than give me the total height
with that should I include it in that original print statement or should I do another print statement or just keep it like so...
print "Enter 1 for Penny\nEnter 5 for Nickel\nEnter 10 for Dime\nEnter 25 for Quarter\nEnter 50 for halfdollar\nEnter 100 for Dollar\nEnter how many coins"
Now witht the last part of enter how many coins how do I associate that with a class I have a class set up for Penny for instance like so
#! /usr/bin/python
# Defining a class
class Coin():
def __init__(slef,weight,height):
self.weight = weight
self.height = height
class Penny(Coin)
def __init__(self)
Coin.__init__(self,2.500,1.52)
Penny = 1
class Nickel(Coin):
def __init__(self):
Coin.__init__(self,5.00,1.95)
Nicke = 5
class Dime(Coin):
def __init__(self):
Coin.__init__(self,2.268,1.35)
Dime = 10
class Quarter(Coin):
def __init__(self):
Coin.__init__(self,5.670,1.75)
Quarter = 25
class HalfDollar(Coin):
def __init__(self):
Coin.__init__(self,11.34,2.15)
HalfDollar = 50
class Dollar(Coin):
def __init__(self):
Coin.__init__(self,8.10,2.00)
Dollar = 100
print "Enter 1 for Penny\nEnter 5 for Nickel\nEnter 10 for Dime\nEnter 25 for Quarter\nEnter 50 for halfdollar\nEnter 100 for Dollar\n"
print "Please enter a number:"
If you name it something generic like cents, you can create a lookup table as follows:
lookup_table = {Penny.cents: Penny, Nickle.cents: Nickle, Dime.cents: Dime, ... }
coin = lookup_table[number_user_entered]()
That way you can dynamically create an instance of the proper class based on the user input.
I think what you are trying to do is something like this:
class Coin():
def __init__(self, name, value, weight, height):
self.name = name
self.value = value
self.weight = weight
self.height = height
definitions = [("dollar", 100, 8.1, 2.0), ...] # define the coins
coins = {data[1]: Coin(*data) for data in definitions} # create Coin instances
There is no need for the Dollar to be a sub-class of Coin, you can just make it an instance with appropriate attribute values.
You can now access each Coin instance within coins by value:
dollar = coins[100]
or use it to access the name:
for value in sorted(coins):
print("Enter {0.value} for a {0.name}".format(coins[value]))
coin_value = int(raw_input("Pick a coin: "))
coin = coins[coin_value]
coin_count = int(raw_input("How many {0}: ".format("{0.name}s".format(coin)
if coin.value > 1 else
"pennies")))
The other answers are both good other ways of dealing with your problem. To strictly solve it the way you defined it:
class Coin():
def __init__(self, weight, height):
self.weight = weight
self.height = height
class Penny(Coin):
value = 1
def __init__(self):
Coin.__init__(self, 2.500, 1.52)
class Nickel(Coin):
value=5
def __init__(self):
Coin.__init__(self, 5.00, 1.95)
class Dime(Coin):
value=10
def __init__(self):
Coin.__init__(self, 2.268, 1.35)
class Quarter(Coin):
value=25
def __init__(self):
Coin.__init__(self, 5.670, 1.75)
class HalfDollar(Coin):
value=50
def __init__(self):
Coin.__init__(self, 11.34, 2.15)
class Dollar(Coin):
value=100
def __init__(self):
Coin.__init__(self, 8.10, 2.00)
mycoin = Penny()
print "A penny is worth", mycoin.value
yourcoin = Quarter()
print "A quarter is worth", yourcoin.value
association = {str(class_obj.value): class_obj for class_obj in (Penny, Nickel, Dime, Quarter, HalfDollar, Dollar)}
print "Enter 1 for Penny\nEnter 5 for Nickel\nEnter 10 for Dime\nEnter 25 for Quarter\nEnter 50 for halfdollar\nEnter 100 for Dollar\n"
value = raw_input("Please enter a number:")
number = raw_input("How many of that coin:")
if value in association:
mycoin = association[value]()
print "total weight:", mycoin.weight * int(number)
print "total height:", mycoin.height * int(number)
How about storing the coin type and amount of coins into a dictionary of a single multidimensional list:
coins = {1:[Penny,[]], 5:[Nickel,[]], 10:[Dime,[]]} # etc...
Then, when you ask the user for coin type and amount, take that value as the key lookup for the dictionary and append that many coins to its list, instantiating the class in the process:
coin_type = raw_input("Enter 1 for Penny\nEnter 5 for Nickel\nEnter 10 for Dime\n:")
coin_amnt = raw_input("Enter amount: ")
for i in range(coin_amnt):
coins[coin_type][1].append(coins[coin_type][0]())
To check total amount of a coin type:
len(coins[coin_type][1])
To check individual instances of a coin type:
for c in coins[coin_type][1]:
print c.weight, c.height
If you wanted to print a coin's type, you can add a __str__() special method to each of your coin classes, and then print the instance as you loop the list.
Hope this helps.