# Create a class, the blueprint for your object class MyTriangle(object): # The __init__ function is called automatically when an object is created def __init__(self, base=0, height=0): # 0 for b & h if nothing is passed in self.base = base self.height = height def setBase( self, base ): self.base = base def getBase( self ): return self.base def setHeight( self, height ): self.height = height def getHeight(self): return self.height def getArea(self): area = self.base * self.height / 2 return area # Create instances of your object (the "houses" made from your blueprint :) # METHOD 1: Create and then set values # Create new empty (0 base, 0 height) triangle object t1 = MyTriangle() # Use methods to set base and height t1.setBase(10) t1.setHeight(5.234) print t1.getArea() # METHOD 2: Pass base and height directly upon creating the object t2 = MyTriangle(10,2.35) print t2.getArea() # Using the getters print t2.getBase() print t2.getHeight() print t2.getArea() # More useful example (the %5.4f means format as float value with up to 5 digits on the left and 4 after the decimal print "Triangle with base %5.4f and height %5.4f has area %5.4f" % ( t2.getBase(), t2.getHeight(), t2.getArea() )
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question