Oct-29-2017, 02:59 PM
I'm not sure on an appropriate title - I hope the one given fits.
I have the following code:
class House(): def __init__(self, roof, side): self.roof = roof self.side = side def volume(self): return self.side ** 3 def price(self, otherSide): if otherSide.volume() < self.side.volume(): return "The house is more expensive" myHouse = House(True, 25.5) print myHouse.volume() print myHouse.price(18.5)Explanation of class
Here I am creating an instance of a House, defining it on whether it has a flat roof or not, and then on its side length, assuming that it is a perfect cube, not including the area of the attic, if it has one.
I define a volume method to compute the volume of the house.
I define a price method to see if one house is smaller than another by comparing the volumes, and then if the house is smaller it is cheaper.
Initial error
This gives me the following problem:
Error:The volume of the house is: 69455.9011819 cubic metres.
Traceback (most recent call last):
File "try2.py", line 18, in <module>
print theHouse.price(18.5)
File "try2.py", line 13, in price
if otherSide.volume() < self.radius.volume():
AttributeError: 'float' object has no attribute 'volume'
So the code works fine for finding the volume of a house when using a particular house as the object of the volume attribute. However, it breaks down when I want to calculate the volume of two houses at once.I think that the issue here is that I am defining the volume method as only using the instance side length to calculate the volume (so it will only ever work for the instance House).
Attempt to solve the problem
So I attempted to solve this problem by putting an additional argument into the volume method, like so:
def volume(self, side2): return side2 ** 3This also throws up an error, which is likely because I am just creating the opposite problem (the method now only works on a side length taken in the argument, and not the instance House as an object).
The error is:
Error:Traceback (most recent call last):
File "try2.py", line 17, in <module>
print theHouse.volume()
TypeError: volume() takes exactly 2 arguments (1 given)
Ultimately I just want to be able to write some code that allows me to use the price method to compare the sizes of two Houses. Any suggestions on how I can edit my code to do this?