python3 exec in 命名空间_python中命名空间中exec类的定义

本文探讨了在Python3中如何在命名空间中使用`exec`函数来动态创建类,例如`FooBarBaz`。通过填充类模板并设置全局命名空间,`exec`能够根据提供的字符串定义执行类。执行后,新创建的类存储在命名空间字典中,可通过其名称访问。最后,代码展示了如何重新分配这个新创建的类到变量`FooBarBaz`。
摘要由CSDN通过智能技术生成

我在Python3上执行此操作,但原理与Python2相同。在

假设你在执行死刑FooBarBaz = namedtuple('FooBarBaz', 'foo bar baz')

在这种情况下,这个代码

^{pr2}$

使用str.format填充类模板,将class_definition设置为字符串,其内容为:class FooBarBaz(tuple):

'FooBarBaz(foo, bar, baz)'

__slots__ = ()

_fields = ('foo', 'bar', 'baz')

def __new__(_cls, foo, bar, baz):

'Create new instance of FooBarBaz(foo, bar, baz)'

return _tuple.__new__(_cls, (foo, bar, baz))

@classmethod

def _make(cls, iterable, new=tuple.__new__, len=len):

'Make a new FooBarBaz object from a sequence or iterable'

result = new(cls, iterable)

if len(result) != 3:

raise TypeError('Expected 3 arguments, got %d' % len(result))

return result

def __repr__(self):

'Return a nicely formatted representation string'

return 'FooBarBaz(foo=%r, bar=%r, baz=%r)' % self

def _asdict(self):

'Return a new OrderedDict which maps field names to their values'

return OrderedDict(zip(self._fields, self))

def _replace(_self, **kwds):

'Return a new FooBarBaz object replacing specified fields with new values'

result = _self._make(map(kwds.pop, ('foo', 'bar', 'baz'), _self))

if kwds:

raise ValueError('Got unexpected field names: %r' % kwds.keys())

return result

def __getnewargs__(self):

'Return self as a plain tuple. Used by copy and pickle.'

return tuple(self)

__dict__ = _property(_asdict)

def __getstate__(self):

'Exclude the OrderedDict from pickling'

pass

foo = _property(_itemgetter(0), doc='Alias for field number 0')

bar = _property(_itemgetter(1), doc='Alias for field number 1')

baz = _property(_itemgetter(2), doc='Alias for field number 2')

现在,代码将创建一个新字典,用作exec的全局命名空间:namespace = dict(__name__='namedtuple_%s' % typename)

我们不使用空字典的原因是,如果有任何跟踪程序将打印出当前模块的__name__,那么它会发现{}设置为{},而不是不存在。在

之后,我们从字符串中执行类定义,并将全局范围作为字典。在exec(class_definition, namespace)

基本上,这将执行上面的类定义,它定义了一个新的模块全局变量FooBarBaz,该变量存储在namespace字典中,该字典又可以通过以下方式获取:result = namespace[typename] # namespace['FooBarBaz']

现在,result是我们新创建的类;然后对它做了一些向导,使其在pickling之后继续存在,然后返回该类。。。在

这段代码可以再次将其赋给变量FooBarBaz:FooBarBaz = namedtuple('FooBarBaz', 'foo bar baz')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值