程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python super explains the use of metaclasses in detail

編輯:Python

Catalog

The definition of a class

One 、 What is metaclass

Two 、 Note the distinction between metaclasses and inherited base classes

3、 ... and 、type The use of metaclasses

Four 、 Use of custom metaclasses

The definition of a class

Objects are created through classes , Like the following code :

# object Is the top-level base class class Work(object): a = 100Mywork = Work() # Instantiation print(Mywork ) # Mywork yes Work An object created <__main__.Work object at 0x101eb4630>print(type(Mywork)) # <class '__main__.Work'>print(type(Work)) # Type is metaclass <class 'type'>

analysis :

You can see the object Mywork It's a class Work Created instance . But you can see Work When the type of is called type Instance of the class created by . namely Mywork —》 Work —》 type establish

In the above example, the object is created dynamically , Class is through the keyword class Declaration defined

that class What is the mystery behind the keywords ?

actually ,class Work(object) This code , Equivalent to Work = type(‘Work’, (objects, ), {“a”:100})

Namely class type The object that created it by instantiation Work, And this Work Just a class , In this way, you can create classes of classes , Namely Python The metaclass of . And in the python The built-in metaclass in is called :type

One 、 What is metaclass

The class used to create the class , Called metaclass

A class is an object created by a metaclass

function type It's actually a metaclass ,type Namely Python The metaclass behind which all classes are created

Two 、 Note the distinction between metaclasses and inherited base classes

type It's a metaclass , All classes are passed through type Created by

object Top level base class , The inherited top-level parent class of all classes is object

3、 ... and 、type The use of metaclasses

You can see type It's lowercase , In general, it will be considered as a function , By looking at the source code, you can see the following defined :

class type(object):"""type(object_or_name, bases, dict)type(object) -> the object's typetype(name, bases, dict) -> a new type"""# Instantiation def __init__(cls, what, bases=None, dict=None): # known special case of type.__init__ """ type(object_or_name, bases, dict) type(object) -> the object's type type(name, bases, dict) -> a new type # (copied from class doc) """ pass# Create a class @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. ( Create and return a new object ) """ pass

type One of the usages of : What type of data to get : type(object) -> the object’s type

a = 100b = "100"c = [11,22,33]print(type(a)) # ======》 <class 'int'>print(type(b)) # ======》 <class 'str'>print(type(c)) # ======》 <class 'list'>

type The second usage of : Create a class :type(object_or_name, bases, dict)

1. When looking at the source code , You can see that at initialization ,init__ Method accepts three parameters ,type In the process of instantiation , It will also recreate a new class , The code that creates the class comes from __new Method , Its parameters are similar to __init__ The method is the same .

2. When calling type When instantiating , Will call automatically first new Method , Call again __init__ Method , Eventually an object will be instantiated , This object is a class .

1. The metaclass type Of init There are methods 3 Parameters :

 1.name: Class name ( String type )
 2.bases: Inherited parent class ( Yuanzu type )
 3.dict: A dictionary of properties and methods ( Dictionary type )

Specific examples :

# adopt class Defining classes class Myclass(object): a = 100 b = 200# adopt type Create a class ( Creating classes dynamically )Myclass1 = type("Myclass1",(object,),{"a":"100","b":"200"})print(Myclass)print(Myclass1)

What if you need to define instance methods and class properties ?, Pass methods and properties in the form of a dictionary

def work(self): print(" This is an example method ——————work————————")# Define class attribute values def init_method(self, aa, bb, cc): self.aa = aa self.bb = bb self.cc = cc# adopt type Create a class ( Creating classes dynamically )Myclass2 = type("Myclass2",(object,),{"a":"100","b":"200","work":work,"work_1":work_1,"__init__":init_method})m = Myclass2(11,22,33)m.work()print(m.aa, m.bb, m.cc)

Four 、 Use of custom metaclasses

Since metaclasses can create classes , You can also customize metaclasses , Custom direct inheritance class type , In the step of customizing metaclasses :

1. Define a class inheritance type

2. rewrite new Method

Specific examples :

# Define a class inheritance typeclass Mytest(type):# rewrite new Method def __new__(cls, type_name, bases, atter, *args, **kwargs): new_cls = super().__new__(cls,type_name, bases, atter) return new_cls # Return a new class M2 = Mytest("M2",(Mytest,),{"atter":100})print(M2) # =====》 <class '__main__.M2'>

Use class Specify a custom metaclass when creating a class

1. When not specified , Default creation is type class

2. Specify a custom metaclass to create a class :metaclass = Specified metaclass

class Myclass(type): """ Custom metaclass """ def __new__(cls, type_name, bases, attrs, *args, **kwargs): new_cls = super().__new__(cls, type_name, bases, attrs) print(" This is Myclass:", type_name, bases, attrs, ) return new_cls# adopt metaclass=xxxx Inherit custom metaclass class Inherited_class(metaclass=Myclass): a = 100 b = 200print(type(Inherited_class)) # ======》 <class '__main__.Myclass'>

This is about Python This is the end of the super detailed article on the use of metaclasses , More about Python Please search the previous articles of SDN or continue to browse the related articles below. I hope you will support SDN more in the future !



  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved