Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9177411
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T17:19:15+00:00 2026-06-17T17:19:15+00:00

I know that there are several posts on this topic, however for what ever

  • 0

I know that there are several posts on this topic, however for what ever reason I can’t get my head around it, or at least implement it. Below is some sample code of what I am trying to do.

Base Class:

class Animal(object):

    def __init__(self, age):
        self._age = age

    def getAge(self):
        return self._age

    def speak(self):
        raise NotImplementedError()

    def speak_twice(self):
        self.speak()
        self.speak()

Sub Class

from Animal import Animal
class Dog(Animal):
    def speak(self):
        print "woff!"

Test Code

mod = __import__("Dog")
spot = mod(5)

After running test Code I get this error:

Traceback (most recent call last):
  File "C:~test.py", line 2, in <module>
    spot = mod(5)
TypeError: 'module' object is not callable

So basically my question is how do I load modules dynamically and initialize them correctly?

EDIT:

I will not know the subclass until runtime

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T17:19:17+00:00Added an answer on June 17, 2026 at 5:19 pm

    You have to import the module itself, then get its class member. You can’t just import the class. Assuming your subclass is in a file accessible from the pythonpath as ‘animal’:

    mod = __import__('animal')
    spot = mod.Dog(5)
    

    When you import a module, the interpreter first looks to see if a module with that name exists in sys.modules, then if it fails to find it there, it searches over the pythonpath looking for a package or module matching the given name. If and when it finds one, it parses the code therein, builds a module object out of it, places it on sys.modules, and returns the module object to the calling scope to be bound to the name it was imported with in the given namespace. All the items in the module (classes, variables, functions) in the module scope (not nested inside something else in the code) are then available as members of that module instance.

    Edit:

    In response to your comment, the real problem is that you are trying to look up an attribute of the module dynamically, not that you are trying to import anything dynamically. The most direct way to do that would be:

    import sub_animal
    getattr(sub_animal, 'Dog')
    

    However, if you are trying to dynamically determine the class to initialize based upon some conditions, you probably want to read up on the factory pattern, and possibly decorators or even metaclasses, so that you can dynamically add subclasses automatically to the factory.

    class AnimalFactory(type):
    
        animal_classes = {}
    
        def __new__(cls, name, bases, attrs):
    
            new_class = super(AnimalFactory, cls).__new__(cls, name, bases, attrs)
            AnimalFactory.animal_classes[name] = new_class
            return new_class
    
        @classmethod
        def build(cls, name, *args, **kwargs):
    
            try:
                klass = cls.animal_classes[name]
            except KeyError:
                raise ValueError('No known animal %s' % name)
            return klass(*args, **kwargs)
    
    class Animal(object):
    
        __metaclass__ = AnimalFactory
    
        def __init__(self, age):
    
            self.age = age
    
        def speak(self):
    
            raise NotImplementedError()
    
    # As long as the file it is implemented in is imported at some point,
    # the following can be anywhere
    
    class Dog(Animal):
    
        def speak(self):
    
            return 'woof'
    
    # And then to use, again, anywhere
    
    new_animal = AnimalFactory.build('Dog', 5)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I know that there are several posts adressing this issue already. However I can't
I know there are already several other posts for this topic, but I've tried
I know there are several other posts on this topic but they still leave
I know that there are several posts about how BAD it is to try
Possible Duplicate: Objective C for Windows I know there are several posts about this
I know there are several other posts with solutions to this, but my current
I know that there are some threads have a similar issue with this thread.
I know that there are lot's of questons on this, but all seem to
I know that there are others posts with solutions on the site but i
I know that there are lots of examples out there on this, but they

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.