开发者

Class from variable

开发者 https://www.devze.com 2023-02-02 09:07 出处:网络
I have a class, trying to instantiate another class, based off of a variable name passed to it. It is complaining that \'str\' object is not callable. What is the proper way to do this?

I have a class, trying to instantiate another class, based off of a variable name passed to it. It is complaining that 'str' object is not callable. What is the proper way to do this?

def MyClass:
    def __init__(self, otherName):
     开发者_高级运维   self.other = otherName()

EDIT: Here is the entirety of my code, is there anything I should do differently? Is eval evil in Python?

#!/usr/bin/python                                                                                                                                                                      

class Model:
    def get_post(self, id):
        # Would query database, perhaps                                                                                                                                                
        return {"title": "Python :: Test Page", "body": "Test page using Python!"}

class Controller:
    def __init__(self, viewName):
        self.model = Model()
        self.view = viewName()

    def main(self):
        post = self.model.get_post(1)
        self.view.display(post)

class View:
    def header(self, item):
        print "Content-type: text/html\r\n\r\n"
        print "<html>"
        print "<head>"
        print "<title>%(title)s</title>" % item
        print "</head>"
        print "<body>"

    def footer(self, item):
        print "</body>"
        print "</html>"

class Blog(View):
    def display(self,item):
 View.header(self,item)
 print "<p>%(body)s</p>" % item
 View.footer(self,item)

c = Controller(Blog)
c.main()


You can do this without using strings at all. You can refer to classes in Python by name, and pass them around just like any other object. So, using your definition of MyClass above, instead of doing:

c = Controller("Blog")

you can use simply:

c = Controller(Blog)

Using eval() for something like this is definitely not recommended.


You should be able to get to your class through the dict that the locals() function returns. Here is a simple class,

class ClassA:
    def __init__(self, word):
        self.word = word

    def __str__(self):
        return "Class A word is '%s'" % self.word

I can create this class from a string of its name, and call it normally,

>>> myclass = locals()['ClassA']('wibble')
>>> print myclass
Class A word is 'wibble'


If you really would like to pass the parameter as a string, you could use eval().

class MyClass: 
    def __init(self, otherName): 
        self.other = eval(otherName)()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号