python使用由字符串变量创建的类的绑定方法
我可能有一个关于python的愚蠢问题,所以请提前原谅我。 我在checks文件夹的check.py文件中有以下类:python使用由字符串变量创建的类的绑定方法,python,methods,Python,Methods,我可能有一个关于python的愚蠢问题,所以请提前原谅我。 我在checks文件夹的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('.') m
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\u name方法?所以我可以得到结果“我的名字是支票”
`您需要更改您的
检查。获取\u 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()
非常感谢。如果你现在问这个问题觉得很愚蠢,但我在这个问题上被困了一个多小时……你在
检查.get_name
中意外地忽略了(self)
参数,因此它被创建为一个staticmethod,而不是一个普通方法。这就是全部。