type()
function can either return the type of an object or create a new type
DEF fn (self, name= "World"): print ("Hello,%s!"% name) Hello = Type ("Hello", (object,), Dict (hello= fn))
h = Hello () >>> H.hello () Hello, world!>>> type (h) out[165]: __main__. hello>>> Type (Hello) out[166]: type
To create a class object, the type()
function passes through 3 parameters in turn:
- The name of the class;
- Inherited parent class Collection, note that Python supports multiple inheritance, if there is only one parent class, do not forget the single element of tuple notation;
- Class's method name and function binding, where we bind the function
fn
to the method name hello
.
Metaclass
in addition to using type()
In addition to dynamically creating classes, you can also use meta-classes (Metaclass) to control the creation behavior of classes.
Once you define Metaclass, you can create a class and finally create an instance.
Metaclass allows you to create classes or modify classes. In other words, you can think of a class as an "instance" created by Metaclass.
For a simple example, this metaclass can add a method to our custom MyList add
:
Definition ListMetaclass
, according to the default habit, the class name of Metaclass always ends with metaclass so that it is clear that this is a metaclass:
# Metaclass is a template for a class, so you must derive from the ' type ' type: class Listmetaclass (type): def __new__ (CLS, name, bases, attrs): attrs['add'lambda self , Value:self.append (value) return type. __new__ (CLS, name, bases, Attrs) class MyList (list, metaclass=listmetaclass): Pass
>>> L = MyList()>>> L.add(1)>> L[1]
__new__()
The parameters that are received by the method are:
The object of the class that is currently ready to be created;
The name of the class;
The collection of parent classes that the class inherits;
The collection of methods for the class.
Application examples
Orm
ORM (Object Relational Mapping), which is objects-relational mapping, is the mapping of a row of a relational database to an object, which is a class that corresponds to a table, so that writing code is simpler and does not have to manipulate SQL statements directly.
Python--OOP advanced--meta class