【发布时间】: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()
【问题讨论】:
-
正确的方法是在 SO 上搜索这个问题,这个问题之前已经被问过很多次了。
-
This answer 可能是您正在寻找的...
-
呃...您发布的代码有效(一旦我修复了 Blog 类中的缩进),我看不到您在哪里使用,也不建议使用,
eval。
标签: python class object new-operator