是否可以动态实例化用字符串编写的 class 而无需将其写入文件?
Is it possible to dynamic instantiate a class written in a string without the need to write it to a file?
如何实例化存储在原始字符串 my_class
without having to save this string into a file first 中的 class?
my_class = r'''class A:
def print(self):
print('Hello World')
'''
my_class_object = string_to_class()
my_class_object.print()
在上面的代码中,我正在寻找函数 string_to_class()
的实现,即 returns my_class
中 class 的一个对象。
以上代码的预期输出是Hello World
。
你只需要使用exec
:它支持动态执行Python代码。
import re
def string_to_object(str_class, *args, **kwargs):
exec(str_class)
class_name = re.search("class ([a-zA-Z_][a-zA-Z0-9_]*)", str_class).group(1)
return locals()[class_name](*args, **kwargs)
可以使用string_to_object
函数自动创建指定对象class:
my_class = '''
class A:
def print(self):
print("Hello World")
'''
a = string_to_object(my_class)
a.print() # Hello World
你也可以构建更复杂的东西:
my_class = '''
class B:
def __init__(self, a, b, c=0, d=1):
self.a = a
self.b = b
self.c = c
self.d = d
'''
b = string_to_object(my_class, 4, 5, c=7)
print(b.a) # 4
print(b.b) # 5
print(b.c) # 7
print(b.d) # 1
还有:
class C:
pass
my_class = '''
class D(C):
pass
'''
d = string_to_object(my_class)
稍微编辑一下字符串怎么样?
my_class_with_new_object = my_class + "\nnew_object = A()"
my_class_with_new_object 将是:
class A:
def print(self):
print('Hello World')
new_object = A()
调用 exec(my_class_with_new_object)
,它将创建一个 new_object
类型的对象 A
然后调用new_object.print()
如何实例化存储在原始字符串 my_class
without having to save this string into a file first 中的 class?
my_class = r'''class A:
def print(self):
print('Hello World')
'''
my_class_object = string_to_class()
my_class_object.print()
在上面的代码中,我正在寻找函数 string_to_class()
的实现,即 returns my_class
中 class 的一个对象。
以上代码的预期输出是Hello World
。
你只需要使用exec
:它支持动态执行Python代码。
import re
def string_to_object(str_class, *args, **kwargs):
exec(str_class)
class_name = re.search("class ([a-zA-Z_][a-zA-Z0-9_]*)", str_class).group(1)
return locals()[class_name](*args, **kwargs)
可以使用string_to_object
函数自动创建指定对象class:
my_class = '''
class A:
def print(self):
print("Hello World")
'''
a = string_to_object(my_class)
a.print() # Hello World
你也可以构建更复杂的东西:
my_class = '''
class B:
def __init__(self, a, b, c=0, d=1):
self.a = a
self.b = b
self.c = c
self.d = d
'''
b = string_to_object(my_class, 4, 5, c=7)
print(b.a) # 4
print(b.b) # 5
print(b.c) # 7
print(b.d) # 1
还有:
class C:
pass
my_class = '''
class D(C):
pass
'''
d = string_to_object(my_class)
稍微编辑一下字符串怎么样?
my_class_with_new_object = my_class + "\nnew_object = A()"
my_class_with_new_object 将是:
class A:
def print(self):
print('Hello World')
new_object = A()
调用 exec(my_class_with_new_object)
,它将创建一个 new_object
类型的对象 A
然后调用new_object.print()