python type() function: dynamically create a class

We know that the type() function is a built-in function of Python, which is usually used to view the specific type of a variable. In fact, there is a more advanced usage of the type() function, which is to create a custom type (that is, to create a class).

There are two syntax formats for the type() function, as follows:

type(obj) 
type(name, bases, dict)

In the above two grammatical formats, the meaning and function of each parameter are:

  • The first syntax format is used to view the specific type of a variable (class object), obj represents a variable or class object.
  • The second grammatical format is used to create a class, where name represents the name of the class; bases represents a tuple, which stores the parent class of the class; dict represents a dictionary, used to represent the attributes or methods defined in the class.

For using the type() function to view the type of a certain variable or class object, due to its simplicity, I will not explain too much here, and give an example directly:

#查看 3.4 的类型
print(type(3.4))
#查看类对象的类型
class CLanguage:
    pass
clangs = CLanguage()
print(type(clangs))

输出结果为:

<class 'float'>
<class '__main__.CLanguage'>

Here is an introduction to another usage of the type() function, that is, to create a new class. Let’s analyze an example first:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
#定义一个实例方法
def say(self):
    print("Python学习者!")
#使用 type() 函数创建类
CLanguage = type("CLanguage",(object,),dict(say = say, name = "我爱学python"))
#创建一个 CLanguage 实例对象
clangs = CLanguage()
#调用 say() 方法和 name 属性
clangs.say()
print(clangs.name)

Note that the Python tuple syntax stipulates that when there is only one element in the (object,) tuple, the last comma (,) cannot be omitted.

As you can see, this program creates a class by type(), its class name is CLanguage, inherited from the objects class, and the class also contains a say() method and a name attribute.

Some readers may ask, how to determine whether a method or an attribute is added to the dict dictionary? Very simple, if the value in the key-value pair is a common variable (such as "I love learning python"), it means that a class attribute is added to the class; on the contrary, if the value is an externally defined function (such as say()), It means that an instance method has been added to the class.

Run the above program, the output result is:

Python学习者!
我爱学python

As you can see, there is no difference between a class created using the type() function and a class defined directly using class. In fact, when we use class to define a class, the underlying Python interpreter still uses type() to create this class.

Guess you like

Origin blog.csdn.net/sinat_38682860/article/details/108681921