#!/usr/bin/python3 # -*- coding: utf-8 -*- # +++++++++++++++++++++++ Lecture 2 starts here # define parent class class Parent: parentAttr = 100 def __init__(self) -> None: print("Calling parent pseudo-constructor") def parent_method(self) -> None: print("Calling parent method") def set_attr(self, attr: int, attr2: int) -> None: # Class variables can be accessed: Parent.parentAttr = attr2 # Class variables can be created: Parent.NewClassAttr = attr # Instance variables can be created or accessed: self.whatever = "hello" def get_attr(self) -> None: print("Parent attribute :", Parent.parentAttr, " and ", Parent.NewClassAttr) class Child(Parent): # define child class def __init__(self) -> None: """ Note, parent __init__ is not called unless you do so explicitly here. """ print("Calling child constructor") self.myInternalVar = "default" def child_method(self, inputVar: str) -> None: print("Calling child method") self.myInternalVar = inputVar def child_get(self) -> None: print(self.myInternalVar) p1 = Parent() p1.set_attr(300, 10) p1.get_attr() print(p1.whatever) p1.whatever = "hey" print(p1.NewClassAttr) print(p1.parentAttr) p2 = Parent() p2.get_attr() # p2.whatever (just an instance variable for p) # We can add a new instance data member p2.randomvar = 37 print(p2.randomvar) # Which constructor is called now? # instance of child c = Child() # child calls its method c.child_method("hey") c.child_get() # calls parent's method c.parent_method() # again call parent's method c.set_attr(200, 100) # again call parent's method c.get_attr()