python字符串可以保存在变量中吗_在python中可以从字符串变量实例化类吗?
一位評論者提到
exec
;這是您將其組合在一起的方式:
def string_to_class(python_text):
local_vars = {}
exec(python_text, {}, local_vars)
# assume just a single new symbol was created (the class), and return it
return list(local_vars.values())[0]
class_template = """
class MyClass(object):
def __init__(self, name):
self.name = name
def print_name(self):
print('My name is: ' + self.name)
@staticmethod
def add_whatever(a, b):
return a + b
"""
MyClass = string_to_class(class_template)
my_class_instance = MyClass('Ben')
print(MyClass.add_whatever(2, 3))
my_class_instance.print_name()
但就像其他一些評論提到的,這不是一種常用的技術,所以要小心。隨著用例變得更加復雜,您也會很快遇到問題:
some_string_that_defines_a_base_class = "case Base..."
some_string_that_defines_a_derived_class = "case Derived(Base):..."
Base = string_to_class(some_string_that_defines_a_base_class)
# this will crash because Base isn't defined in the scope that the string
# is being evaluated with
Derived = string_to_class(some_string_that_defines_a_derived_class)
您可以通過直接調用來修復它。
exec
(the
string_to_class
函數的功能還不夠強大),但它很快就變得很難使用:我甚至沒有提到如何
import
S還可以。還有其他一些技術(函數裝飾器、元類)可以讓你做你想做的事,這些技術會減少你的痛苦,但是有時候
執行程序
真的是你唯一的選擇。
總結
以上是生活随笔為你收集整理的python字符串可以保存在变量中吗_在python中可以从字符串变量实例化类吗?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SQL Server有这些属性吗
- 下一篇: python zipfile压缩_Pyt