Created
January 6, 2017 08:32
-
-
Save suriyadeepan/77ebea26e6410a81301d6c40c5d935bf to your computer and use it in GitHub Desktop.
Demonstration of class in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# all classes are sub-classes/children of the ultimate parent class -> object (i think) | |
class Rectangle(object): | |
# the constructor | |
def __init__(self, length, breadth): | |
# class's properties | |
self.length = length | |
self.breadth = breadth | |
def area(self): | |
return self.length * self.breadth | |
def perimeter(self): | |
return 2 * (self.length + self.breadth) | |
# end of class | |
''' | |
How to instantiate/create an object of type Rectangle? | |
''' | |
r1 = Rectangle(2,3) # __init__ is called here | |
r2 = Rectangle(4,6) # another object | |
r3 = Rectangle(1,3) # another object | |
# how do you call a method of a class? | |
area1 = r1.area() | |
peri3 = r3.perimeter() | |
print(area1) | |
print(peri3) | |
# access properties of a class | |
r2_l = r2.length | |
r2_b = r2.breadth | |
print(r2_l, r2_b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment