Construct object (Rectangle) without arguments when __init__ of class requires parameters - python

I am working on an assignment that requires a Rectangle class that computes the area and perimeters given. We are given the main() function already and have to build around it. It seems to run up until it gets to b = Rectangle() where it says it
requires exactly 3 arguments.
Here is my code:
class Shape(object):
def __init__(self):
pass
def area():
pass
def perimeter():
pass
class Rectangle(Shape):
def __init__(self, width, height):
Shape.__init__(self)
self.width = width
self.height = height
def area(self):
area = self.height * self.width
return area
def perimeter(self):
perimeter = 2*(self.width+self.height)
return perimeter
def getStats():
print "Width: %d" % b.width
print "Height: %d" % b.height
print "Area: %d" % b.area
print "Perimeter: %d" % b.perimeter
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()
main()
How to get the second rectangle to work without changing the main function?

Read on python's support for default arguments for "constructors"... Something like
def __init__(self, width = 0, height = 0)

Related

Direct printing in class - python

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

Working with classes in python

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()

Object Oriented Python - rectangle using classes and functions

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())

How to use a class's return in other class?

Here is what I wrote. A program about Geometric Object and I'm trying to use the GeometricObject.str(self) in the class Circle's str function, but it doesn't work. I tried many ways and it still has some error.
import math
class GeometricObject(object):
def __init__(self, color = "white", filled = True):
self.color = color
self.filled = filled
def getColor(self):
return self.color
def setColor(self, color):
self.color = color
def isFilled(self):
return self.filled
def setFilled(self, filled):
self.filled = filled
def __str__(self):
return "color: " + self.color + \
" and filled: " + str(self.filled)
class Circle(object):
def __init__(self, radius = 1, color = "white", filled = True):
self.radius = radius
self.color = color
self.filled = filled
def __str__(self):
return "Circle: radius = " + str(self.radius) + \
GeometricObject.__str__(self)
def getArea(self):
return (math.pi * self.radius**2)
def getPerimeter(self):
return (math.pi * 2 * self.radius)
class Triangle(object):
def __init__(self, side1 = 1, side2 = 1, side3 = 1, color = "white", filled = True):
self.side1 = side1
self.side2 = side2
self.side3 = side3
self.color = color
self,filled = filled
def __str__(self):
return "Triangle: side1 = " + str(self.side1) + \
" side2 = " + str(self.side2) + \
" side3 = " + str(self.side3) + \
" color: " + str(self.color) +\
" filled: " + str(self.filled)
def getArea(self):
s = (side1 + side2 + side3) / 2
area = sqrt(s(s - side1)(s - side2)(s - side3))
return area
def getPerimter(self):
return (side1 + side2 + side3)
def main():
#Testing Circle class
print "Entering input values for a circle"
r = input('Enter value for radius: ')
c1 = Circle(r)
print c1
print "%.2f" % c1.getArea()
print "%.2f" % c1.getPerimeter()
print c1.getColor()
print c1.isFilled()
#Testing Triangle class
print "\nEntering input values for a traingle"
s1 = input('Enter value for side1: ')
s2 = input('Enter value for side2: ')
s3 = input('Enter value for side3: ')
color = raw_input('Enter color of the triangle: ')
filled = input('Is the triangle filled (1/0)? ')
filled = (filled == 1)
t1 = Triangle(s1, s2, s3, color, filled)
print t1
print "%.2f" % t1.getArea()
print "%.2f" % t1.getPerimeter()
print t1.getColor()
print t1.isFilled()
main()
But it keeps telling me that,
Entering input values for a circle
Enter value for radius: 1
Traceback (most recent call last):
File "C:\Users\wxwdd_000\Desktop\CSC131\Lab_5.py", line 94, in <module>
main()
File "C:\Users\wxwdd_000\Desktop\CSC131\Lab_5.py", line 71, in main
print c1
File "C:\Users\wxwdd_000\Desktop\CSC131\Lab_5.py", line 32, in __str__
GeometricObject.__str__(self)
TypeError: unbound method __str__() must be called with GeometricObject instance as first argument (got Circle instance instead)
>>>
How can i fix the str function?
You forgot to have your subclasses inherit from GeometricObject.
Change these:
class Circle(object):
class Triangle(object):
to these:
class Circle(GeometricObject):
class Triangle(GeometricObject):
Additional note: You should probably call GeometricObject.__init__ to set the properties Triangle and Circle inherit from GeometricObject instead of assigning them directly. If GeometricObject.__init__ did something more complex with its arguments, the subclass constructors would either not handle it properly or become too tied to the superclass's implementation details.
I f you want to inherit it should be like this
class circle(GeometricObject): and also you can call GeometricObjects str method using super() inbuilt function call like super(circle,self).str(arg)
Hope this helps

Python property being ignored, acting like an attribute

I've got this RoomPlaceholder class with a distance property; when you set the distance property, it should automatically calculate what the x and y of the class should be, based on a random angle and the distance.
class RoomPlaceholder:
def __init__(self, width, height):
self.width = width
self.height = height
self.id = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(8))
self.angle = Util.getRandomAngle() # = random.random() * math.pi * 2
self.distance = 0
#property
def distance(self):
print "gamma"
return self._distance
#distance.setter
def distance(self, value):
print "delta"
self._distance = value
coords = Util.getXYByDist(value, self.angle) # translates angle and distance into integer (x, y)
print coords
self._x = coords[0]
self._y = coords[1]
#property
def x(self):
return self._x
#property
def y(self):
return self._y
def __repr__(self):
return "%s: [%sx%s] # (%s, %s) Distance: %s. Angle: %s." % (self.id, self.width, self.height, self.x, self.y, self.distance, self.angle)
if __name__ == "__main__":
room = RoomPlaceholder(5,5)
print "%s\n" % room.distance
room.distance = 10
print "%s\n" % room.distance
print room
pass
However, it's not working. Based on the output from the console, it looks like it's treating distance as an attribute rather than a property; note that I've got print statements in both the getter ("gamma") and setter ("delta") methods, but we never see either in the output when I get or set the distance:
Traceback (most recent call last):0
File "D:\Dropbox\Programming\Python\DungeonGenerator\NewDungeonGenerator.py", line 142, in <module>
10
print room
File "D:\Dropbox\Programming\Python\DungeonGenerator\NewDungeonGenerator.py", line 132, in __repr__
return "%s: [%sx%s] # (%s, %s) Distance: %s. Angle: %s." % (self.id, self.width, self.height, self.x, self.y, self.distance, self.angle)
File "D:\Dropbox\Programming\Python\DungeonGenerator\NewDungeonGenerator.py", line 97, in x
return self._x
AttributeError: RoomPlaceholder instance has no attribute '_x'
[Finished in 0.0s]
I'm using Python 2.7, and this is being run via Sublime Text 3 in Windows 7.
property only works for new-style classes. You need to make RoomPlaceholder a subclass of object by declaring it thusly:
class RoomPlaceholder(object):
# etc.

Categories

Resources