在Python中,你可以使用`globals()`函数或者`locals()`函数将字符串转换为对应的类。以下是使用这些函数的示例:
使用`globals()`函数
class Data:
def __init__(self):
self.name = 'kelly'
def hello(self):
print('hello')
使用字符串获取类
Data_class = globals()['Data']
创建类的实例
res = Data_class().hello()
print(res)
使用`locals()`函数
class Data:
def __init__(self):
self.name = 'kelly'
def hello(self):
print('hello')
使用字符串获取类
Data_class = locals()['Data']
创建类的实例
res = Data_class().hello()
print(res)
使用`getattr()`函数
class Data:
def __init__(self):
self.name = 'kelly'
def hello(self):
print('hello')
使用字符串获取类
Data_class = globals()['Data']
创建类的实例
res = getattr(Data_class, 'hello')()
print(res)
使用`operator.attrgetter`函数
import operator
class Foo:
pass
f = Foo()
f.bar = Foo()
f.bar.baz = Foo()
f.bar.baz.quux = 'Found me!'
使用attrgetter获取属性值
print(operator.attrgetter('bar.baz.quux')(f)) 输出:Found me!
使用`importlib.import_module`和`getattr`
import importlib
假设有一个模块a.py,其中包含类A
a.py
class A():
def __init__(self):
print('A')
动态导入模块并获取类
module_name = 'a'
class_name = 'A'
module = importlib.import_module(module_name)
A_class = getattr(module, class_name)
创建类的实例
a_instance = A_class()
以上方法可以帮助你根据字符串动态地获取并实例化Python类。请根据你的具体需求选择合适的方法