Use type() to dynamically create classes

Because classes are also objects, we can create classes while the program is running. Python is a dynamic language. The biggest difference between dynamic languages ​​and static languages ​​is that the definitions of functions and classes are not defined at compile time, but dynamically created at runtime. Before, we first understand the type() function.

First we create a new hello.py module, and then define a Hello class.

class Hello(object):
    def hello(self, name='Py'):
        print('Hello,', name)

Then reference the hello module in another module and output the corresponding information. The type() function is used to view the type of a type and variable.

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
from com.twowater.hello import Hello
h = Hello()
h.hello()
print(type(Hello))
print(type(h))

What is the output result?

Hello, Py
<class 'type'>
<class 'com.twowater.hello.Hello'>

As mentioned above, the type() function can check the type of a type or variable. Hello is a class, its type is type, and h is an instance, its type is com.twowater .hello.Hello. The previous com.twowater is my package name, and the hello module is under this package name.

Think more about it here. In the above example, we use the type() function to check the type of a type or variable. The type of a Hello class was checked, and the printed result was: <class 'type'> . In fact, the type() function can not only return the type of an object, but also create new types. The definition of class is dynamically created at runtime, and the way to create a class is to use the type() function. For example, we can create the Hello class in the above example through the type() function. See the following code for details:

# -*- coding: UTF-8 -*-
def printHello(self, name='Py'):
    # 定义一个打印 Hello 的函数
    print('Hello,', name)
# 创建一个 Hello 类
Hello = type('Hello', (object,), dict(hello=printHello))
# 实例化 Hello 类
h = Hello()
# 调用 Hello 类的方法
h.hello()
# 查看 Hello class 的类型
print(type(Hello))
# 查看实例 h 的类型
print(type(h))

The output results are as follows:

Hello, Py
<class 'type'>
<class '__main__.Hello'>

Here, you need to first understand the pass Parameter description of the type() function to create a class object:

1. The name of the class, such as Hello in the example

2. The collection of inherited parent classes. Note that Python supports multiple inheritance. , if there is only one parent class, the tuple should be written using a single element; in the example, the object class is inherited. Because it is a single-element tuple, it is written as (object,)

3. The method name of the class is bound to the function; In the example, the function printHello is bound to the method name hello

The specific pattern is as follows:

type(class name, tuple of parent class (can be empty for inheritance), Dictionary containing attributes (name and value))

Okay, after understanding the specific parameter usage, let's look at the output results. We can see that the class created through the type() function and the direct write class is exactly the same, because when the Python interpreter encounters a class definition, it just scans the syntax of the class definition, and then calls the type() function to create the class.

But generally, we use the class ***... method to define classes, but the type() function also allows us to create classes. In other words, a dynamic language itself supports the dynamic creation of classes during runtime, which is very different from a static language. To create a class during the runtime of a static language, you must construct a source code string and then call the compiler, or use some tools to generate a word Section code implementation is essentially dynamic compilation, which can be very complicated.

As you can see, in Python, classes are also objects, and you can create classes dynamically. In fact, this is what Python does behind the scenes when you use the keyword class, and this is achieved through metaclasses.

Continuing Learning
||
submitReset Code