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()
Related
I am new in 'class' methods, so sorry if somebody feel resentful. Every many people know this example:
class Rectangle:
def __init__(self, length, breadth, unit_cost=0):
self.length = length
self.breadth = breadth
self.unit_cost = unit_cost
def get_perimeter(self):
return 2 * (self.length + self.breadth)
def get_area(self):
return self.length * self.breadth
def calculate_cost(self):
area = self.get_area()
return area * self.unit_cost
Now to get information we need to do such operation:
r = Rectangle(160, 120, 2000)
print("Area of Rectangle: %s cm^2" % (r.get_area()))
print("Cost of rectangular field: Rs. %s " %(r.calculate_cost()))
Result:
Area of Rectangle: 19200 cm^2
Cost of rectangular field: Rs. 38400000
But I dont do it this I need write this:
Rectangle(160, 120, 2000)
and get answer right now:
Area of Rectangle: 19200 cm^2
Cost of rectangular field: Rs. 38400000
I can use ordinary def myfunction: but I would like to do it by class.
Thanks for every help!
If you implement the code you wrote in the print statements as the class __str__ method, you'll get that result by printing the class itself:
class Rectangle:
def __init__(self, length, breadth, unit_cost=0):
self.length = length
self.breadth = breadth
self.unit_cost = unit_cost
def __str__(self):
return "Area of Rectangle: %s cm^2\nCost of rectangular field: Rs. %s " % (self.get_area(), self.calculate_cost())
def get_perimeter(self):
return 2 * (self.length + self.breadth)
def get_area(self):
return self.length * self.breadth
def calculate_cost(self):
area = self.get_area()
return area * self.unit_cost
And the output:
>>> print(Rectangle(160, 120, 2000))
Area of Rectangle: 19200 cm^2
Cost of rectangular field: Rs. 38400000
This is a better design decision than adding a print statement to __init__, since it's relatively painless to add a print statement around the Rectangle() call, and it's more flexbile because you can still choose whether you want to display the output or not.
Use __repr__ to make a printable representation of your class, then add a print statement from within __init__ if you want to avoid using print outside of the class (you can make this optional).
class Rectangle:
def __init__(self, length, breadth, unit_cost=0):
self.length = length
self.breadth = breadth
self.unit_cost = unit_cost
print(self)
def __repr__(self):
area_str = "Area of Rectangle: %s cm^2" % (self.get_area())
cost_str = "Cost of rectangular field: Rs. %s " %(self.calculate_cost())
return area_str + "\n" + cost_str
def get_perimeter(self):
return 2 * (self.length + self.breadth)
def get_area(self):
return self.length * self.breadth
def calculate_cost(self):
area = self.get_area()
return area * self.unit_cost
Output:
r = Rectangle(160, 120, 2000)
Area of Rectangle: 19200 cm^2
Cost of rectangular field: Rs. 38400000
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
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 creating a program in Python that will utilize object oriented programming to print the properties of a given rectangle. The project has these given constraints:
The purpose of this lab is to give you practice creating your own
object. You will be given a main function that expects an instance of
the (yet undefined) Rectangle object. Your job is to determine what
attributes and methods the Rectangle class requires and create a class
that will satisfy the requirements.
Add only one feature at a time
You may need to comment out parts of the main function for testing
Constructor should take 0, 1, or 2 parameters (illustrating polymorphism)
Your class should be a subclass of something (illustrating inheritance)
Your class should have methods and properties (illustrating encapsulation)
Make your instance variables hidden (using the __ trick)
Add setter and getter methods for each instance variable
Use properties to encapsulate instance variable access
Not all instance variables are real... Some are derived, and should be write-only
You may not substantially change the main function (unless you're doing the blackbelt challenge)
Be sure to add the needed code to run the main function when needed
Here is the rubric
Code: main() function is relatively unchanged 3
Code: Rectangle class is declared with defaults so it supports 0, 1 and 2 parameters 3
Code: Instantiates Rectangle(5,7) 2
Code: Instantiates Rectangle() 2
Code: Rectangle class defines __ instance variables 2
Code: Defines getters and setters for each instance variable 2
Code: Rectangle class include area and perimeter methods 4
Code: Rectangle class inherits from something, even if it's object 2
Code: Rectangle class defines width and length properties 4
Code: Rectangle includes derived read-only instance variables 2
Code: Invokes main when the python file is executed as main 2
Code: Rectangle class defines getStats() method that returns a string 4
Execution: prints Rectangle a: 1
Execution: prints area: 35 1
Execution: prints perimeter: 24 1
Execution: prints Rectangle b: 1
Execution: prints width: 10 1
Execution: prints height: 20 1
Execution: prints area: 200 1
Execution: prints perimeter: 60 1
Score 40
I am given this code to start off with:
def main():
print "Rectangle a:"
a = Rectangle(5, 7)
print "area: %d" % a.area
print "perimeter: %d" % a.perimeter
print ""
print "Rectangle b:"
b = Rectangle()
b.width = 10
b.height = 20
print b.getStats()
I am supposed to get this output:
Rectangle a:
area: 35
perimeter: 24
Rectangle b:
width: 10
height: 20
area: 200
perimeter: 60
I have gotten this far but I can not get Rectangle B to print the width and height Can you please take a look?
class Rectangle:
def __init__(self, width=0, height=0):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * self.height + 2 * self.width
def setWidth(self, width):
self.width = width
def setHeight(self, height):
self.height = height
def getStats(self):
return "area: %s\nperimeter: %s" % (self.area(), self.perimeter())
def main():
print ""
print "Rectangle a:"
a = Rectangle(5, 7)
print "area: %s" % a.area()
print "perimeter: %s" % a.perimeter()
print ""
print "Rectangle b:"
b = Rectangle()
b.width = 10
b.height = 20
print b.getStats()
print ""
main()
I am currently getting this output:
Rectangle a:
area: 35
perimeter: 24
Rectangle b:
area: 200
perimeter: 60
Process finished with exit code 0
NOTE: This homework is an exact assignment from my computer science class. While you are welcome to get help from sites like stack overflow, you are still responsible for your own work, and if you turn in code from this site (which may or may not be acceptable) we will know, and we will consider it academic misconduct. We may also have made some quiet changes to the assignment, so if you turn this answer in without careful consideration, you are unlikely to get full credit even
Not sure I got your question right, but you may want to try:
def getStats(self):
return "width: %s\nheight: %s\narea: %s\nperimeter: %s" % (self.width, self.height, self.area(), self.perimeter())
To satisfy requirements 4 and 6, I would suggest something like:
class Shape(object):
def area(self):
raise NotImplementedError
def perimeter(self):
raise NotImplementedError
class Rectangle(Shape):
def __init__(self, width=0, height=0):
super(Rectangle, self).__init__() # this is useless in this case, but it's good practice
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * self.height + 2 * self.width
#property
def width(self):
return self.__width
#property
def height(self):
return self.__height
#width.setter
def width(self, width):
self.__width = width
#height.setter
def height(self, height):
self.__height = height
def getStats(self):
return "width: %s\nheight: %s\narea: %s\nperimeter: %s" % (self.width, self.height, self.area(), self.perimeter())
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()