mercredi 19 avril 2017

Importing a class using a variable

So, I have a set of classes defined in instrument.rules.py

class ClassABC(object):
    def name(self):
        return 'ClassABC'

class ClassXYZ(object):
    def name(self):
        return 'ClassXYZ'

In another code, I want to use a variable to call the class. Therefore my code is something like this:

from instrument.basecontract import BaseContract #Default class
import instrument.rules as rules

def getClass(className):
    if hasattr(rules,className):
        return getattr(rules,className)()
    else:
        return BaseContract()

My problem is, when I execute the following:

x = getClass('ClassXYZ')
print(x.name())

y = getClass('SomeDefault')
print(y.name())

I get the following error:

IndexError: single positional indexer is out-of-bounds






Comments
0 Comments

0 commentaires:

Enregistrer un commentaire