【问题标题】:Class from variable来自变量的类
【发布时间】:2010-12-30 22:10:53
【问题描述】:

我有一个类,试图实例化另一个类,基于传递给它的变量名。它抱怨'str'对象不可调用。这样做的正确方法是什么?

def MyClass:
    def __init__(self, otherName):
        self.other = otherName()

编辑:这是我的全部代码,有什么我应该做的不同的吗? eval 在 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()

【问题讨论】:

标签: python class object new-operator


【解决方案1】:

你完全可以使用字符串来做到这一点。您可以通过名称引用 Python 中的类,并像传递任何其他对象一样传递它们。所以,使用你上面对MyClass 的定义,而不是这样做:

c = Controller("Blog")

你可以简单地使用:

c = Controller(Blog)

绝对不建议将eval() 用于此类操作。

【讨论】:

    【解决方案2】:

    您应该能够通过 locals() 函数返回的 dict 进入您的班级。这是一个简单的类,

    class ClassA:
        def __init__(self, word):
            self.word = word
    
        def __str__(self):
            return "Class A word is '%s'" % self.word
    

    我可以从它的名字的字符串创建这个类,并正常调用它,

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

    【讨论】:

      【解决方案3】:

      如果你真的想将参数作为字符串传递,你可以使用 eval()。

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

      【讨论】:

      • 使用eval 应该是最后的手段。
      • eval 通常会导致奇怪的不可重现的错误,几乎在所有情况下都应该避免。 Python 为进行古怪的元编程提供了极大的灵活性,而无需对构造代码进行文字评估。
      猜你喜欢
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 2021-06-15
      • 2016-11-05
      • 2013-11-07
      • 1970-01-01
      • 1970-01-01
      • 2018-08-14
      相关资源
      最近更新 更多