Method Analysis of Dynamic Class Creation in python

  • 2021-07-01 07:51:44
  • OfStack

This paper illustrates the method of dynamically creating classes in python. Share it for your reference, as follows:

As a dynamic language, python, how to create classes dynamically at runtime (python Creating classes dynamically), which is sometimes useful in programming, dynamically generating classes and giving corresponding attributes and methods. Generally speaking, there are two ways:

1. Hard-coded implementation according to conditions. 2. Using type metaclass.

Hard-coded according to conditions


def choose_class(name):
 if name == 'foo':
  class Foo(object):
   pass
  return Foo #  Return 1 Classes, not instances 
 else:
  class Bar(object):
   pass
  return Bar
MyClass = choose_class('foo') 
print MyClass #  Return 1 Classes, not instances 
print MyClass() #  Create 1 Instances 

After running, the result is:

< class '__main__.Foo' >
< __main__.Foo object at 0x00BA8370 >

But in fact, this is not so dynamic, and you have to write the whole definition of class in the program. Since class is an object, it must be created by something. In python, when you use the class keyword, python will automatically create the object. What can be done manually? It is the type method. This is a very special method that can create a class. The syntax of type is as follows:


type(name of the class, 
  tuple of the parent class (for inheritance, can be empty), 
  dictionary containing attributes names and values)

According to this grammar rule, do the following example:


def echo_msg(self):
 print self.msg
print '===dynamic create class==='+ '*'*50
MyClass = type('MyClass',(object,),{"a":123,"b":"summer","msg":"test message","echo_msg":echo_msg})
print MyClass.a
myclass = MyClass()
myclass.echo_msg()
print myclass.a,myclass.b
print '===dynamic create subclass==='+ '*'*50
MySubClass = type('MySubClass',(MyClass,),{"c":"c-value"})
print MySubClass.c,MySubClass.a,MySubClass.b
print issubclass(MySubClass, MyClass)
mysubclass = MySubClass()
mysubclass.echo_msg()

The running results are as follows:

===dynamic create class===**************************************************
123
test message
123 summer
===dynamic create subclass===**************************************************
c-value 123 summer
True
test message

This example uses type to create an MyClass class, and then creates MySubClass to inherit MyClass class, and binds attributes and methods. MySubClass also binds its own unique properties, while inheriting the properties and methods of the base class.

In this way, the dynamic creation of classes in python is mainly due to the type method. Why type is so powerful? The ultimate reason is that type is metaclass, a metaclass, a class used to create classes. For example:


Class=MetaClass()
instance=Class()

What is metaclass and how to use it? Later articles will explain python metaclass in detail.

More readers who are interested in Python can check the topics of this site: "Introduction and Advanced Tutorial of Python Object-Oriented Programming", "Python Data Structure and Algorithm Tutorial", "Summary of Python Function Use Skills", "Summary of Python String Operation Skills", "Summary of Python Coding Operation Skills" and "Introduction and Advanced Classic Tutorial of Python"

I hope this article is helpful to everyone's Python programming.


Related articles: