0

我正在使用一个函数来实例化 python 类。

Hers 是类结构

from DB.models import ApiKey,ServiceProvider

class SMSMrg( object ):
    _instance = None
    class Singleton:
        def __init__(self):
            self.username = None
            self.password = None
            self.allsp = []
            self.classnames = {}
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(SMSMrg, cls).__new__(
                                cls, *args, **kwargs)
        return cls._instance

    def loadsettings(self):

        get_all_sp = ServiceProvider.objects.filter(status = False)
        for (options,obj) in enumerate(get_all_sp):
            cla = str(obj.class_Name)
            self.classnames[cla] = cla
        print self.classnames

        for (options,obj) in enumerate(get_all_sp):
            cla = str(obj.class_Name)
            class_object = self.classnames[cla](obj.userName,obj.password,obj.sendingurl)

       # self.allsp = get_all_sp 
    def send(self):
        print "+++++++++++++++++++== Global send "


if __name__ == "__main__":

    b = SMSMrg()
    b.loadsettings()

我已经将类名存储在数据库中,并且我已经在不同的文件上定义了每个类结构。

Likecla 将包含一个类名。

但是当我调用上面的函数时,我得到了类型错误。

Traceback (most recent call last):
  File "allsms.py", line 30, in <module>
    b.loadsettings()
  File "allsms.py", line 21, in loadsettings
    class_object = cla(obj.userName,obj.password,obj.sendingurl)
TypeError: 'str' object is not callable

请告诉我如何实例化我的 db 中存在名称的所有类。

4

4 回答 4

1

cla = str(SERVIVEPROVIDER)您转换SERVIVEPROVIDER为字符串的行上。在下一行你试图调用它,因此你得到一个错误......

于 2013-02-05T06:36:35.837 回答
1
 # Means `cla` is pointing to a string
cla = str(SERVIVEPROVIDER)

# there is no function called `cla` now it contains a string
cla(obj.userName,obj.password,obj.sendingurl)
于 2013-02-05T06:36:42.140 回答
0

正如您所说cla,包含类的名称,这意味着您不能将其用作可调用对象。

您可以构建一个dict并从那里获取类对象:

from somemodule import SomeClass

class TheClass(object):
    def __init__(self, username, password, url):
        #do stuff

class AnOtherClass(object):
    def __init__(self, username, password, url):
        # do stuff

CLASS_NAMES_TO_CLASSES = {
    # Note: TheClass is *not* a string, is the class!!!
    'FirstName': TheClass,
    'SecondName': AnOtherClass,
    'SomeClass': SomeClass,
    }

class SMSMrg(object):
    #do stuff
    def loadsettings(self):
       get_all_sp = ServiceProvider.objects.filter(status = True)
       for obj in get_all_sp:
           SERVIVEPROVIDER = obj.class_Name
           cla = str(SERVIVEPROVIDER)
           class_object = CLASS_NAMES_TO_CLASSES[cla](obj.userName,obj.password,obj.sendingurl)

此方法要求您能够构建这样的dict,因此您要么提前知道哪些类最终会出现在数据库中,要么您不能使用此方法。

请注意,这不是CLASS_NAMES_TO_CLASSES将字符串映射到字符串的字典。它将字符串映射到类对象。如果从模块中导入类,则必须将其放入字典中。SomeClass

另一种方法可以eval用来评估类名,但如果数据库包含来自用户的数据(这是不安全的),你应该避免这种情况。

另一个可能有用的选项是避免保存类名,而是pickle直接保存实例。

于 2013-02-05T06:37:22.783 回答
0

Please tell me how can instansiate all the classes which names are present in my db .

Try this:

class A(object): pass
class B(object): pass

class_names = {'first': A, 'second': B}
obj = class_names['first']()
type(obj)
<class 'yourmodule.A'>

Or, if your classes are stored somewhere else, say in a module called mymodule:

import mymodule
obj = getattr(mymodule, 'A')()
于 2013-02-05T06:51:19.943 回答