简体   繁体   中英

What means of namespace object in Python

How to use types.new_class method in python3.3 later?
The following is sigunature.

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

How to use exec_body?
exec_body must be callable object, and it take a argument ns . (maybe it means namespace )
what type object should pass to ns ?
According to documentation of new_class ,

The exec_body argument is a callback that is used to populate the freshly created class namespace. 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.

I have no idea meaning of above description about ns and 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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