Skip to content

Instantly share code, notes, and snippets.

@charlesreid1
Created September 16, 2018 03:01
Show Gist options
  • Save charlesreid1/620d202b6df15c983fd5ceb1588f4965 to your computer and use it in GitHub Desktop.
Save charlesreid1/620d202b6df15c983fd5ceb1588f4965 to your computer and use it in GitHub Desktop.
Python OOP: Controlling parent class behavior from child class
"""
Python Object Oriented Programming:
Control Parent Class Behavior from Child Class
Author: Charles Reid
Date: 2018-09-15
This is a short demo of how to conditionally
control the behavior of a parent class from a
child class. This is accomplished by setting
a class attribute LABEL in the derived class,
and referencing that attribute in the parent
class constructor (where it will be available).
This is a way of dealing with the case where
you have a parent class that performs a task
common to a bunch of child classes, but it
needs information from the child class.
"""
class Parent(object):
def __init__(self):
if self.LABEL is None:
raise Exception("self.LABEL is undefined!")
if self.LABEL=='red':
self.red()
elif self.LABEL=='blue':
self.blue()
def red(self):
print("red fish")
def blue(self):
print("blue fish")
class RedChild(Parent):
LABEL = 'red'
def __init__(self):
super().__init__()
class BlueChild(Parent):
LABEL = 'blue'
def __init__(self):
super().__init__()
if __name__=="__main__":
r = RedChild()
b = BlueChild()
"""
Outputs:
red_fish
blue_fish
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment