Created
September 18, 2015 02:53
-
-
Save schie/548d3fb3d0abc84fe713 to your computer and use it in GitHub Desktop.
Example of how classes work 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
# import the math module (this will be used in Circle class) | |
import math | |
# created a generic shape class | |
class Shape: | |
# the function to initialize the shape | |
def __init__(self, width, height): | |
# the properties of the shape | |
self.width = width | |
self.height = height | |
# the function to get area, but not implelmented | |
def get_area(self): | |
pass | |
# overridden 'tostring' method that will return all properties | |
# see lines 49, 53, 57 | |
def __str__(self): | |
return str(vars(self)) | |
# rectangle is a subclass of shape | |
class Rectangle(Shape): | |
# overloaded get_ara method: w * h | |
def get_area(self): | |
return self.width * self.height; | |
# Square is a subclass of Rectangle | |
class Square(Rectangle): | |
# added a new __init__ method | |
def __init__(self, side_length): | |
# sets width and height to side_length | |
self.width = self.height = side_length | |
# circle is a subclass of Shape | |
class Circle(Shape): | |
# custom init w/ radius | |
def __init__(self, radius): | |
# make new radius paramter | |
self.radius = radius | |
# set the width and height (optional, but good to stay consistent) | |
self.width = self.height = radius * 2 | |
# area of circle: 2πr | |
def get_area(self): | |
return math.pi * 2 * self.radius | |
shape = Shape(4, 5) | |
print(str(shape)) # prints {'width': 4, 'height': 5} | |
print(shape.get_area()) # prints None | |
sq = Square(4) | |
print(str(sq)) # prints {'width': 4, 'height': 4} | |
print(sq.get_area()) # prints 16 | |
c = Circle(4) | |
print(str(c)) # prints {'width': 8, 'radius': 4, 'height': 8} | |
print(c.get_area()) # prints 25.1327412287 | |
Author
schie
commented
Sep 18, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment