Direct printing in class - python - 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

Related

my method returns an address at the link of a value

This is an exercise that is not part of the training on the site, I do not understand why when I want to display the return value of the energy method of my satellite class, I receive an address on the console.
Zoe satellite speed = 40.0m / s.
<bound method Satellite.energie of <__ main __. Satellite object at 0x01A5E610 >>
Zoe satellite speed = 70.0m / s.
<bound method Satellite.energie of <__ main __. Satellite object at 0x01A5E610 >>
This is my code:
class Satellite (object):
"" "Satellite for instantiating objects simulating satellites
artificial launched into space, around the earth. "" "
def __init __ (self, name, mass = 100, speed = 0):
self.name = name
self.mass = mass
speed choke = speed
def impulse (self, force, duration):
"" "will vary the speed of the satellite." ""
speed self = speed self + (force * duration) / mass self
def energy (self):
"" "will refer to the program calling the kinetic energy value of the satellite" ""
return_val = self.mass * self.speed ** 2/2
return return_val
def display_speed (self):
"" "will display the name of the satellite and its current speed." ""
print ("satellite speed {0} = {1} m / s.". format (self.name, self.speed))
s1 = Satellite ('Zoe', mass = 250, speed = 10)
s1.pulse (500, 15)
s1.display_speed ()
print (s1.energy)
s1.pulse (500, 15)
s1.display_speed ()
print (s1.energy)
Your energy method is wrong, and it should have given a syntax error:
def energy (self):
"" "will refer to the program calling the kinetic energy value of the satellite" ""
return_val = self.mass * self.speed ** 2/2
return return_val
Not to mention, you need to invoke the energy method as well:
s1.pulse (500, 15)
s1.display_speed ()
print(s1.energy())
s1.pulse (500, 15)
s1.display_speed ()
print(s1.energy())
You are trying to overwrite the return statement and use it as a variable, which is just WRONG. There are other mistypings/issues in your code as well, but this one definitely seems to be main issue.
Rather than calling the function Satellite.energy(), you're trying to access the property Satellite.energy - if you change it to print(s1.energy()), it should display correctly!
As a note, some of your code has been formatted wrong here so it doesn't run - this works for me:
class Satellite (object):
"" "Satellite for instantiating objects simulating satellites artificial launched into space, around the earth. "" "
def __init__ (self, name, mass = 100, speed = 0):
self.name = name
self.mass = mass
self.speed = speed
def impulse (self, force, duration):
"" "will vary the speed of the satellite." ""
return self.speed + (force * duration) / self.mass
def energy (self):
"" "will refer to the program calling the kinetic energy value of the satellite" ""
return self.mass * self.speed ** 2/2
def display_speed (self):
"" "will display the name of the satellite and its current speed." ""
print ("satellite speed {0} = {1} m / s.". format (self.name, self.speed))
s1 = Satellite ('Zoe', mass = 250, speed = 10)
s1.impulse (500, 15)
s1.display_speed ()
print (s1.energy())
s1.impulse (500, 15)
s1.display_speed ()
print (s1.energy())

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

python 2.7 Instantiating class in another class

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

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

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)

Categories

Resources