我正在编写一个 python (3.2+) 插件库,我想创建一个函数,该函数将创建一些从配置文件自动处理的变量。
用例如下(类变量):
class X:
option(y=0)
def __init__(self):
pass
(实例变量):
class Y:
def __init__(self):
option(y=0)
期权草案代码如下:
def option(**kwargs):
frame = inspect.stack()[1][0]
locals_ = frame.f_locals
if locals_ == frame.f_globals:
raise SyntaxError('option() can only be used in a class definition')
if '__module__' in locals_:
# TODO
else:
for name, value in kwargs.items():
if not name in locals_["self"].__class__.__dict__:
setattr(locals_["self"].__class__, name, VirtualOption('_'+name, static=False))
setattr(locals_["self"], '_'+name,value)
I have problem the first case, when option is declared as class variable. 是否有可能以某种方式获得对使用此函数的类的引用(例如对类 X)?