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?
Namespace is a way to implement scope. In Python, each package, module, class, function and method function owns a "namespace" in which variable names are resolved. When a function, module or package is evaluated (that is, starts execution), a namespace is created. Think of it as an "evaluation context".
So if you want to create a namespace, you just need to call a function, instantiate an object, import a module or import a package. For example, we can create a class called Namespace and when you create an object of that class, you're basically creating a namespace.
Prominent examples for namespaces include file systems, which assign names to files. Some programming languages organize their variables and subroutines in namespaces. Computer networks and distributed systems assign names to resources, such as computers, printers, websites, and remote files.
There are three types of Python namespaces- global, local, and built-in. It's the same with a variable scope in python. Also, the 'global' keyword lets us refer to a name in a global scope.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With