Dynamic(at Runtime) Code Decisions
The changing of strategy at runtime, creation of new objects etc. at runtime is very important and essential part of flexible development process, esp. if creating of APIs for software.
There are couple of ways to achieve the functionality.
I) Factory Functions :-
Need to create instances of the Dog or Cat class(subclass of Animal super class) at runtime, on the user request or as code demands.
Create the function which calls the desired Python Object(function, class etc.) depending on the argument parsed.
eg.
# Super class, Animal
class Animal(object):
pass
# First sub class, Dog
class Dog(Animal):
def __init__(self, *args, **kwargs):
self.name = args[0]
self.category = kwargs.get('category')
# Second sub class, Cat
class Cat(Animal):
def __init__(self, *args, **kwargs):
self.name = args[0]
self.category = kwargs.get('category')
# Factory Function
def createAnimal(*args, **kwargs):
# Python Object dictionary
animalDict = { 'dog': Dog, 'cat': Cat }
return animalDict.get(kwargs.get('category').lower())(*args, **kwargs)
# Test code
animal1 = createAnimal('Puppy', category='Dog')
print '%s is a %s' % (animal1.name, animal1.category)
animal2 = createAnimal('Pussy', category='Cat')
print '%s is a %s' % (animal2.name, animal2.category)
II) Constructor Method:-
Python Class constructor __new__ can be used on the super class to decide and instantiate any of its subclass in accordance to the parsed
arguments.
eg.
# Super class, Animal
class Animal(object):
def __new__(cls, *args, **kwargs):
if kwargs.get('category').lower() == 'dog':
return super(Animal, cls).__new__(Dog, *args, **kwargs)
elif kwargs.get('category').lower() == 'cat':
return super(Animal, cls).__new__(Cat, *args, **kwargs)
# First sub class, Dog
class Dog(Animal):
def __init__(self, *args, **kwargs):
self.name = args[0]
self.category = kwargs.get('category')
# Second sub class, Cat
class Cat(Animal):
def __init__(self, *args, **kwargs):
self.name = args[0]
self.category = kwargs.get('category')
# Test code
animal1 = Animal('Puppy', category='Dog')
print '%s is a %s' % (animal1.name, animal1.category)
animal2 = Animal('Pussy', category='Cat')
print '%s is a %s' % (animal2.name, anima2.category)
HTML Comment Box is loading comments...