我有一个关于python的愚蠢问题,请提前原谅我。 我在文件夹check.py文件夹中检查了以下类:
class Check(object):
def __init__(self):
print "I am initialized"
def get_name():
return "my name is check"
此类通过带有以下函数的变量字符串加载:
def get_class( kls ):
parts = kls.split('.')
module = ".".join(parts[:-1])
m = __import__( module )
for comp in parts[1:]:
m = getattr(m, comp)
return m
我有理由创建一个由字符串变量定义的类,所以不要试图绕过它。
现在我运行以下内容:
from checks import * # the __init__.py is correct of this one
s="check"
cl=get_class("checks."+s+"."+s.title())
a=cl()
print str(a)
print "name="+str(a.get_name)
我得到以下输出:
I am initialized
<checks.check.Check object at 0x0000000002DB8940>
name=<bound method Check.get_name of <checks.check.Check object at 0x0000000002DB8940>>
现在我的问题:有什么方法可以访问Check.get_name方法吗?所以我可以得到结果“我的名字是检查”?
`
答案 0 :(得分:2)
您需要更改Check.get_name
定义:
class Check(object):
def __init__(self):
print "I am initialized"
def get_name(self):
return "my name is check"
然后您可以使用以下代码访问它:
from checks import * # the __init__.py is correct of this one
s="check"
cl=get_class("checks."+s+"."+s.title())
a=cl()
print a.get_name()