I try to get the final answer as (32, 56) but then it throws me the result as (32, 112). I'm sure this happens because my double function issue after it has been calling twice, one for getting length and another for getting width. Below is my example codes.
class Box:
## Constructor declaration.
def __init__(self, length, width):
self.__length = length
self.__width = width
## A method that doubles the size of a box.
def double(self):
self.__length = self.get_length() * 2
self.__width = self.get_width() * 2
return self
## A method that gets length of a box.
def get_length(self):
return self.__length
## A method that gets width of a box.
def get_width(self):
return self.__width
def combine(self, other):
self.__length = self.__length + other.get_length()
self.__width = self.__width + other.get_width()
return self
box1 = Box(5,10)
box2 = Box(3,4)
box3 = Box(5,10)
box1.combine(box3)
box2.double()
box1.combine(box2)
print(box1.double().get_length())
print(box1.double().get_width())
Literally what you said in your question - you're doubling it twice.
box1.double()
print(box1.get_length()) # 32
print(box1.get_width()) # 56
Related
class Square(object):
def __init__(self, height="0", width="0"):
self.height = height
self.width = width
#property #This is a getter which allows us to refer to our fields inside of our __init__ method
def height(self):
print("Retrieving the height")
return self.__height #__height: __ to be a private field and protect our data
#height.setter #This is our setter to prevent us from putting bad data into our Square()
def height(self, value): #making sure that the value passed in is a digit
if value.isdigit(): #can use isfloat() for better results, but I'm using isdigit() anyway
self.__height = value
else: #if the value is NOT a digit
print("Please only enter a digit")
#Now we do the same for our width...
#property
def width(self, value):
print("Retrieving the width")
return self.__width
#width.setter
def width(self, value):
if value.isdigit():
self.__width = value
else:
print("Please enter a digit")
def getArea(self):
return int(self.__width) * int(self.__height)
def main():
UserSquare = Square() #My empty square object which I have to define as the user's square (UserSquare)
height = raw_input("Enter Height : ")
width = raw_input("Enter Width : ")
#Now I use the getters (#property) and setters to set everything
UserSquare.height = height #calling the user Square Object to set the heght
UserSquare.width = width # calling the user Square Object to set the width
print("Height :", UserSquare.height)
print("Height :", UserSquare.width)
print("Therefore, The area is :", UserSquare.getArea())
main()
#The reason I used getters and setters was so that I can just refer to my height method and width method as height and width
#If I didn't have those getters and setters, I would have to refer to them as height() and width()
The program asks the user to input a height and width, and then it calculates and shows the area of their 'square' (actually rectangle)
But it comes up with the TypeError in my title when I enter my width.
Can someone please tell me how I can fix this problem?
I am using PYTHON 2.7
class Square(object):
def __init__(self, height="0", width="0"):
self.height = height
self.width = width
#property #This is a getter which allows us to refer to our fields inside of our __init__ method
def height(self):
print("Retrieving the height")
return self.__height #__height: __ to be a private field and protect our data
#height.setter #This is our setter to prevent us from putting bad data into our Square()
def height(self, value): #making sure that the value passed in is a digit
if value.isdigit(): #can use isfloat() for better results, but I'm using isdigit() anyway
self.__height = value
else: #if the value is NOT a digit
print("Please only enter a digit")
#Now we do the same for our width...
#property
def width(self):
print("Retrieving the width")
return self.__width
#width.setter
def width(self, value):
if value.isdigit():
self.__width = value
else:
print("Please enter a digit")
def getArea(self):
return int(self.__width) * int(self.__height)
def main():
UserSquare = Square() #My empty square object which I have to define as the user's square (UserSquare)
height = raw_input("Enter Height : ")
width = raw_input("Enter Width : ")
#Now I use the getters (#property) and setters to set everything
UserSquare.height = height #calling the user Square Object to set the heght
UserSquare.width = width # calling the user Square Object to set the width
print("Height :", UserSquare.height)
print("Height :", UserSquare.width)
print("Therefore, The area is :", UserSquare.getArea())
main()
I had to make my def width(self, value) into def width under #property.
thanks everyone
I'm just beginning working with object-oriented programming. I have created some classes and am trying to complete the rectangle class. Any and all help is appreciated.
I'm confused about when you need to refer to self and when you can just create variables. For example, in defining the length of the rectangle, I don't know if I should call the variable self.length or just length, and I haven't been able to find any rectangle classes defined in this way.
import math
class Point (object):
# constructor
def __init__ (self, x = 0, y = 0):
self.x = x
self.y = y
# get distance
def dist (self, other):
return math.hypot (self.x - other.x, self.y - other.y)
# get a string representation of a Point object
def __str__ (self):
return '(' + str(self.x) + ", " + str(self.y) + ")"
# test for equality
def __eq__ (self, other):
tol = 1.0e-16
return ((abs (self.x - other.x) < tol) and (abs(self.y - other.y) < tol))
class Circle (object):
# constructor
def __init__ (self, radius = 1, x = 0, y = 0):
self.radius = radius
self.center = Point (x, y)
# compute cirumference
def circumference (self):
return 2.0 * math.pi * self.radius
# compute area
def area (self):
return math.pi * self.radius * self.radius
# determine if point is strictly inside circle
def point_inside (self, p):
return (self.center.dist(p) < self.radius)
# determine if a circle is strictly inside this circle
def circle_inside (self, c):
distance = self.center.dist (c.center)
return (distance + c.radius) < self.radius
# determine if a circle c intersects this circle (non-zero area of overlap)
def does_intersect (self, c):
# string representation of a circle
def __str__ (self):
# test for equality of radius
def __eq__ (self, other):
tol = 1.0e-16
class Rectangle (object):
# constructor
def __init__ (self, ul_x = 0, ul_y = 1, lr_x = 1, lr_y = 0):
if ((ul_x < lr_x) and (ul_y > lr_y)):
self.ul = Point (ul_x, ul_y)
self.lr = Point (lr_x, lr_y)
else:
self.ul = Point (0, 1)
self.lr = Point (1, 0)
# determine length of Rectangle
def length (self):
# determine width of Rectangle
def width (self):
# determine the perimeter
def perimeter (self):
# determine the area
def area (self):
# determine if a point is strictly inside the Rectangle
def point_inside (self, p)
# determine if another Rectangle is inside this Rectangle
def rectangle_inside (self, r):
# determine if two Rectangles overlap
def does_intersect (self, other):
# determine the smallest rectangle that circumscribes a circle
def rect_circumscribe (self, c):
# give string representation of a rectangle
def __str__ (self):
# determine if two rectangles have the same length and width
def __eq__ (self, other):
Basically, setting a value to self.length gives you the ability to access this value from other functions inside the class and from outside of the class. If you set a value to length, you are able to access this variable only in the current function inside the class.
Just a start, try to continue yourself:
class Rectangle (object):
# constructor
def __init__ (self, ul_x = 0, ul_y = 1, lr_x = 1, lr_y = 0):
# Called if you say: my_rectancle = Rectangle (-10, 10, 10, -10)
# Puts parameters in fields of your newly created object of class Rectancle
self.ul_x = ul_x
self.ul_y = ul_y
self.lr_x = lr_x
self.lr_y = lr_y
# compute cirumference
def circumference (self):
return 2 * (self.ur_x - self.lr_x) + 2 * (self.ul_y - self.lr_y)
# compute area
def area (self):
return (self.ur_x - self.lr_x) * (self.ul_y - self.lr_y)
[EDIT]
With regard to the additional code in your comment, it's quite close to what it should be. With some corrections:
# determine length of Rectangle
def length (self):
return self.ul_y - self.lr_y
# determine width of Rectangle
def width (self):
return self.lr_x - self.ul_x
# self. has been added, since e.g. lr_x is not a parameter
# of the width function, but a field of the object you make
# by instantiation: 'rectangle = Rectangle (10, 20, 100, 200)'
# After that, self refers to the object 'rectangle' you created,
# which has class 'Rectangle'.
#
# Note that a class is a type.
# You can have a type 'Dog'.
# Dog 'fluffy' is an instance of that class, so a particular dog.
# In the methods (functions) of 'Dog', 'self' refers to the particular
# dog you're working with.
# determine the perimeter
def perimeter (self):
return 2 * self.width () + 2 * self.length ()
# Note the () after width and length.
# They're needed because width and length are
# function calls (they DO something) rather than fields (data)
# You could also have stored width and length into fields,
# just like the constructor did with ul_x, ul_y, lr_x and lr_y,
# storing them in self.ul_x, self.ul_y etc.
# Then the braces wouldn't have been needed.
# But also out some superfluous braces here
# Multiplication goes before addition anyhow
# And return returns everything after it, no braces needed.
# determine the area
def area (self):
return self.width () * self.length ()
So, how far did you get now?
I am working on a simple cuboid class program in python and I am very new to it all so I have a few questions about the first version of my code:
from math import *
class Cuboid:
def __init__(self,length,width,height):
self.length=length
self.width=width
self.height=height
self.LSA=0
self.SA=0
self.volume=0
def getDimensions(self):
return self.length
return self.width
return self.height
def LateralSurfaceArea(self):
LSA=2*((self.length*self.height)+(self.width*self.height))
return LSA
def SurfaceArea(self):
SA=2*((self.length*self.width)+(self.width*self.height)+(self.height*self.length))
return SA
def Volume(self):
Volume=self.length*self.width*self.height
return volume
My first question, is this the proper way to set up a class and initialize it?
second question, are there any glowing errors in this part? I am working out of a textbook teaching myself and it has no examples.
Finally my main:
from cuboid import *
def main():
cb = Cuboid(3, 4, 5)
l, w, h = cb.getDimensions()
print("The length of the cuboid is", l)
print("The width of the cuboid is", w)
print("The height of the cuboid is", h)
print("lateral surface area=", cb.LateralSurfaceArea())
print("surface area=", cb.SurfaceArea())
print("volume=", cb.Volume())
main()
when I run my main function I get the following error:
l, w, h = cb.getDimensions()
TypeError: 'int' object is not iterable
Does anyone have any idea why this error is coming up and anyway I can get around it? sorry I know I'm only supposed to ask a specific question but for the sake of learning properly id rather make sure I'm going in the right direction as classes are new to me.
When returning multiple values, you don't use multiple return statements. Instead, you return a tuple:
return (self.length, self.width, self.height)
In your case, only the first return statement gets executed thus passing a single int to the caller. It then tries to unpack that value into the three variables you specified by iterating over it. The single value that was returned isn't iterable, hence the error.
A slightly cleaned-up version:
class Cuboid:
def __init__(self, length, width, height):
self.length = length
self.width = width
self.height = height
#property
def lateral_surface_area(self):
front_area = self.length * self.height
side_area = self.width * self.height
return 2 * (front_area + side_area)
#property
def surface_area(self):
top_area = self.length * self.width
front_area = self.length * self.height
side_area = self.width * self.height
return 2 * (top_area + front_area + side_area)
#property
def volume(self):
return self.length * self.width * self.height
def main():
cube = Cuboid(3, 4, 5)
print("The length of the cuboid is", cube.length)
print("The width of the cuboid is", cube.width )
print("The height of the cuboid is", cube.height)
print("Lateral surface area =", cube.lateral_surface_area)
print("Surface area =", cube.surface_area)
print("Volume =", cube.volume)
if __name__=="__main__":
main()
I am writing a class, Tbeam (Python 2.7.8 in IPython notebook 2.2.0) that calculates values for a reinforced concrete T beam. The flange and web of the Tbeam are considered to be objects of the class Rectangle. I instantiate a flange and web from the class Rectangle in the class Tbeam, and create methods to calculate the overall depth (d) and area (area) of the Tbeam.
class Rectangle:
"""A class to create simple rectangle with dimensions width (b) and
height (d). """
def __init__(self, b, d ):
"""Return a rectangle object whose name is *name* and default
dimensions are width = 1, height = 1.
"""
self.width = b
self.height = d
def area(self):
"""Computes the area of a rectangle"""
return self.width * self.height
def inertia(self):
"""Computes the moment of inertia of a rectangle,
with respect to the centroid."""
return self.width*math.pow(self.height,3)/12.0
def perim(self):
"""Calculates the perimeter of a rectangle"""
return 2*(self.width+self.height)
def centroid(self):
"""Calculates the centroid of a rectangle"""
return self.height/2.0
def d(self):
"""Returns the height of the rectangle."""
return self.height
def bf(self):
"""Returns the width of the rectangle."""
return self.width
-
class Tbeam:
"""A class to create T beams with dimensions:
bf = width of top flange,
tf = thickness of top flange,
d = height of web,
bw = width of web. """
def __init__(self, bf,tf,d,bw):
self.bf = bf
self.tf = tf
self.d = d
self.bw = bw
self.flange = Rectangle(bf,tf)
self.web = Rectangle(bw,d)
def area(self):
area =self.flange.area + self.web.area
def d(self):
"""Returns the total height of the Tbeam"""
return self.flange.d + self.web.d
-
When I execute the test cell
# Test Tbeam
t1 = Tbeam(60.0, 5.0,27.0,12.0)
print t1.d
print t1.area
-
I get the following:
27.0
bound method Tbeam.area of <__main__.Tbeam instance at 0x7f8888478758
27.0 is correct but I do not understand the second response for print t1.area. I assume my definition for area is incorrect but I don't know how to correct the problem.
Many thanks
Ron
You're printing t1.area which is a method. You want to print the result of calling the method, so print t1.area().
area method is defined as
def area(self):
area =self.flange.area + self.web.area
but should be defined as
def area(self):
area =self.flange.area() + self.web.area()
I am new to python and I am trying to write class RectangleCollection. class Rectangle is given, and I need to write class RectangleCollection part.
class RectangleCollection has one list instance variable, rectangles, that should initially refer to an empty list.
get_same_area_rects takes a number as a parameter and returns a list of all Rectangles from the rectangles list that have that area.
class Rectangle:
""" A rectangle with a width and height. """
def __init__(self, w, h):
""" (Rectangle, number, number)
Create a new rectangle of width w and height h.
>>> r = Rectangle(1, 2)
>>> r.width
1
>>> r.height
2
"""
self.width = w
self.height = h
def area(self):
""" (Rectangle) -> number
Return the area of this rectangle.
>>> r = Rectangle(10, 20)
>>> r.area()
200
"""
return self.width * self.height
These are what I have done :
class RectangleCollection:
def __init__(self):
""" (RectangleCollection) -> NoneType
>>> rc = RectangleCollection()
>>> rc.rectangles
[]
"""
self.rectangles = []
def get_same_area_rects(self, number):
"""
>>>rc = RectangleCollection()
>>>r1 = Rectangle(10, 20)
>>>r2 = Rectangle(15, 20)
>>> r3 = Rectangle(20, 10)
>>>rc.rectangles.extend([r1, r2, r3])
>>>res = rc.get_same_area_rects(200)
>>>res == [r1, r3]
True
"""
self.number = number
a = self.rectangles.expend(self.area())
if number == self.rectangles.area():
return True
return False
but for get_same_area_rects part, I always get False..
I have no idea what I did wrong. Please help
i think it is because rc.rectangles gives me r1,r2,r3 addresses, not the areas. I should get [200,300,200] but I get the addresses. I think this is why I always get False.. How can I fix this problem?
How about use filter function to only take rectangles whose area is number
def get_same_area_rects(self, number):
return filter(lambda rect: rect.area() == number, self.rectangles)
CSC108 right? This function within class is not asking you to return True of False, it is asking you to call this function to get a list of rectangles that their area is 200
You have a typographic error in your code. It should be:
extend not expend as follows:
a = self.rectangles.extend(self.area())
if number == self.rectangles.extend(self.area()):
return True
Or simply:
a = self.rectangles.extend(self.area())
if number == a:
return True
You have to create a temporary list and then loop over the rectangles. This is because since we have to return a list which has the same area, we would need to use the rectangle.area() to compare if they are true or not and then add into the list.
def get_same_area_rects(self, number):
temp_list = []
for rectangle in self.rectangles:
if number == rectangle.area():
temp_list.append(rectangle)
return temp_list
hope it helps :)