Created
March 20, 2019 03:05
-
-
Save jonepl/b9bd1dfc68733c1c46f879d688d8488c to your computer and use it in GitHub Desktop.
Simple snippet of Python Inheritance
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
class Shape(object) : | |
def __init__(self) : | |
self.dummyVar = 9 | |
def area(self) : | |
raise NotImplementedError("You must implement area method in the {0} sub class.".format(self.__class__.__name__)) | |
def perimeter(self) : | |
raise NotImplementedError("You must implement area method in the {0} sub class".format(self.__class__.__name__)) | |
def randomJunk(self) : | |
print("Random Junk!") | |
class Rectangle(Shape) : | |
def __init__(self, length, width) : | |
self.length = length | |
self.width = width | |
super().__init__() | |
def area(self) : | |
return self.length * self.width | |
def perimeter(self) : | |
return self.length * 2 + self.width * 2 | |
class Square(Rectangle) : | |
def __init__(self, side) : | |
self.side = side | |
super().__init__(side, side) | |
def main() : | |
rectangle = Rectangle(5, 8) | |
square = Square(6) | |
# Method calls through one level of inheritance | |
print(rectangle.area()) | |
print(rectangle.perimeter()) | |
rectangle.randomJunk() | |
# Method calls through one level of inheritance | |
print(square.area()) | |
print(square.length) | |
# Call through two levels of inheritance | |
print(square.dummyVar) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment