Skip to content

Instantly share code, notes, and snippets.

@npatta01
Last active August 29, 2015 14:17
Show Gist options
  • Save npatta01/89a26cbcca3b378f6894 to your computer and use it in GitHub Desktop.
Save npatta01/89a26cbcca3b378f6894 to your computer and use it in GitHub Desktop.
Example of dynamic loading in python
class Cat(object):
def make_sound(self):
print("Cat says Meow")
def hide(self, num):
print("Regular cat is hiding for %s secs"% num)
class BrownCat(object):
def make_sound(self):
print("Brown Cat says Meow")
def hide(self, num):
print("Brown cat is hiding for %s secs"% num)
import importlib
def main():
#module name without the .py extension
cat_module_name="cat"
#Cat class in cat module
cat_cls_name="Cat"
#BrwonCat class in cat module
brown_cat_cls_name="BrownCat"
#get cat module
cat_module=importlib.import_module(cat_module_name)
#create cat instance
cat_inst = getattr(cat_module, cat_cls_name)()
#create brown cat instance
brow_cat_inst = getattr(cat_module, brown_cat_cls_name)()
#call cat methods
cat_inst.make_sound()
cat_inst.hide(5)
#call brown cat methods
brow_cat_inst.make_sound()
brow_cat_inst.hide(10)
if __name__ == "__main__":
main()
Cat says Meow
Regular cat is hiding for 5 secs
Brown Cat says Meow
Brown cat is hiding for 10 secs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment