简体   繁体   English

Python中命名空间对象的含义

[英]What means of namespace object in Python

How to use types.new_class method in python3.3 later? 如何在python3.3中使用types.new_class方法?
The following is sigunature. 以下是sigunature。

types.new_class(name, bases=(), kwds=None, exec_body=None)  

How to use exec_body? 如何使用exec_body?
exec_body must be callable object, and it take a argument ns . exec_body必须是可调用对象,并且它采用ns参数。 (maybe it means namespace ) (也许这意味着namespace
what type object should pass to ns ? 什么类型的对象应该传递给ns
According to documentation of new_class , 根据new_class文档,

The exec_body argument is a callback that is used to populate the freshly created class namespace. exec_body参数是一个回调函数,用于填充新创建的类名称空间。 It should accept the class namespace as its sole argument and update the namespace directly with the class contents. 它应该接受类名称空间作为其唯一参数,并直接使用类内容更新名称空间。 If no callback is provided, it has the same effect as passing in lambda ns: ns. 如果没有提供回调,则它与传入lambda ns:ns具有相同的效果。

I have no idea meaning of above description about ns and exec_body. 关于ns和exec_body,我不知道上面描述的含义。
How can I use this function? 我该如何使用此功能?

The namespace is a dictionary. 命名空间是一个字典。 You fill it with the attributes (including methods) that you want your new class object to have. 您可以使用希望新类对象具有的属性(包括方法)填充它。 Here's a simple demo. 这是一个简单的演示。

import types

def body(ns):
    def __init__(self, a):
        self.a = a

    d = {
        '__doc__': 'A test class',
        'some_cls_attr': 42,
        '__repr__': lambda self: 'Test(a={})'.format(self.a),
        '__init__': __init__,
    }
    ns.update(d)

Test = types.new_class('Test', bases=(), kwds=None, exec_body=body)

print(Test.some_cls_attr)
print(Test('hello'))
#help(Test)

output 产量

42
Test(a=hello)

Of course, for this simple example it's much more sensible to use the normal class creation syntax. 当然,对于这个简单的例子,使用普通的类创建语法会更加明智。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM