dynamically loading classes

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • divus
    New Member
    • Sep 2008
    • 2

    dynamically loading classes

    I am fairly new to python and I do not know if what I would like to do is possible; however, I have done some searching to see if I could find an answer - I found nothing.

    I have a file with classes in it. I would like to import all the classes and then run each one through a function without having to type each one out, is this possible?

    IE. I want to do something like this:

    Code:
    from myfile import *
    from project.control import admin
    
    for myclass in myfile:
      admin.register(myclass)
    instead of doing:

    Code:
    from myfile import *
    from project.control import admin
    
    admin.register(classA)
    admin.register(classB)
    ...
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Originally posted by divus
    I am fairly new to python and I do not know if what I would like to do is possible; however, I have done some searching to see if I could find an answer - I found nothing.

    I have a file with classes in it. I would like to import all the classes and then run each one through a function without having to type each one out, is this possible?

    IE. I want to do something like this:

    [CODE=Python]
    from myfile import *
    from project.control import admin

    for myclass in myfile:
    admin.register( myclass)
    [/CODE]

    instead of doing:

    Code:
    from myfile import *
    from project.control import admin
    
    admin.register(classA)
    admin.register(classB)
    ...
    Import the module, and you can use dir(module) to access the objects. Example:[code=Python]>>> import math
    >>> for s in dir(math):
    ... if not s.startswith('_ _'):
    ... print getattr(math, s)
    ...
    <built-in function acos>
    <built-in function asin>
    <built-in function atan>
    <built-in function atan2>
    <built-in function ceil>
    <built-in function cos>
    <built-in function cosh>
    <built-in function degrees>
    2.71828182846
    <built-in function exp>
    <built-in function fabs>
    <built-in function floor>
    <built-in function fmod>
    <built-in function frexp>
    <built-in function hypot>
    <built-in function ldexp>
    <built-in function log>
    <built-in function log10>
    <built-in function modf>
    3.14159265359
    <built-in function pow>
    <built-in function radians>
    <built-in function sin>
    <built-in function sinh>
    <built-in function sqrt>
    <built-in function tan>
    <built-in function tanh>
    >>> [/code]

    Comment

    • divus
      New Member
      • Sep 2008
      • 2

      #3
      I think this is exactly what I need!

      Thank you!

      Comment

      Working...