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

The most difficult point to master Python: metaclass

編輯:Python

Preface

I'm learning python In the process, everyone must look at the source code , In the process of looking at the source code, you will see some metaclasses , But it seems very difficult to understand , That's because we don't know enough about metaclasses .

Let's have a chat today python The metaclass , See where the metaclass is sacred .

Necessary knowledge reserve

● Before talking about metaclasses, we must first understand the concepts of classes and objects and the creation process of classes , This is crucial , It depends on whether we can really understand and use metaclasses correctly .

● Class and object concepts

1、 class : A collection of objects with the same properties and methods ( abstract )

2、 object : The entity of a class is an object ( Specifically ) Create classes in the traditional way

Create classes in the traditional way

1、 Code demonstration
class Demo:
def __init__(self,name):
self.name = name
print(" initialization self.name = ",self.name)
if __name__ == '__main__'
print("Demo Who created the class :",type(Demo))
print("Demo The parent of a class :",Demo.__bases__)
cl = Demo(" Lao Wang ")
print("cl Who created the instance :",type(cl))
2、 Output :
Demo Who created the class :<class 'type'>
Demo The parent of a class :(<class 'object'>,)
initialization self.name = Lao Wang
cl Who created the instance :<class '__main__.Demo'>
3、 Conclusion :
a、 class (Demo) By type Created
b、 object (cl) By class (Demo) Created
c、 Class based (Demo) Create objects (cl), Execute parent class first (object) Of __new__() Method , Returns the object (cl)

type Create a class

1、 We know from the example above , Class is created by type Created , So can we just go through type To create classes
2、type grammar
type(" Class name ",( Which class to inherit ,),{" The attribute name ":" Property value "," Method name key":" Method name "})
3、 Code demonstration
demo = type("Demo",(object,),{"name":" Lao Wang "})
print(" Class name :",demo.__name__)
print("Demo Who created the class :",type(demo))
cl = demo()
print("cl Who created the instance :",type(cl))
4、 Output :
Class name :Demo
Demo Who created the class :<class 'type'>
cl Who created the instance :<class '__main__.Demo'>
5、 Conclusion
a、 class (Demo) By type Created
b、 object (cl) By class (Demo) Created
c、 Direct use type Create classes and create classes in the traditional way , The effect is as like as two peas

The metaclass

● Concept

1、 What is metaclass : The class used to create other classes is called metaclass
2、 Think about a problem , Can we create other classes based on our own defined classes ?

Customize metaclasses and create classes

1、 Code demonstration
class Demo1(type):
def __init__(self,*args, **kwargs):
super().__init__(*args, **kwargs)
class Demo2(metaclass=Demo1):
def __init__(self,name,age):
self.name = name
self.age = age
print("Demo2 Instance properties of class :name={}".format(self.name))
print("Demo2 Instance properties of class :age={}".format(self.age))
if __name__ == '__main__':
print("Demo2 Who created it :",type(Demo2))
cl = Demo2(" Lao Wang ","20")
2、 Output :
Demo2 Who created it :<class '__main__.Demo1'>
Demo2 Instance properties of class :name= Lao Wang
Demo2 Instance properties of class :age=20
3、 Conclusion
a、 class (Demo2) By Demo1 Created
b、 You can create other classes through custom classes

Metaclass classic application

1、 Implement singleton pattern through metaclass
2、 The singleton pattern : During program execution, a class is instantiated only once
3、 principle : Intervene in the process of class instantiation , If it has been instantiated, it will not be instantiated
class Demo1(type):
def __init__(self,name,bases, attrs):
super().__init__(name,bases, attrs)
self._instance = None
def __call__(self, *args, **kwargs):
# Determine whether an object has been created , Called without creating __new__() Method to create an object , Once created, do not call __new__() Method , Directly return the created object
if self._instance is None:
self._instance = self.__new__(self,*args, **kwargs)
# Call your own class (Demo2) Instantiation method of
self.__init__(self._instance,*args, **kwargs)
return self._instance
class Demo2(metaclass=Demo1):
def __init__(self,name,age):
self.name = name
self.age = age
print("Demo2 Instance properties of class :name={}".format(self.name))
print("Demo2 Instance properties of class :age={}".format(self.age))
if __name__ == '__main__':
print("Demo2 Who created it :",type(Demo2))
cl1 = Demo2(" Lao Wang ",20)
cl2 = Demo2(" Lao Wang ",20)
print("cl1 The memory address of the instance :",id(cl1))
print("cl2 The memory address of the instance :",id(cl1))
print("cl1 Whether it is cl2",cl1 is cl2)
4、 Output :
Demo2 Who created it :<class '__main__.Demo1'>
Demo2 Instance properties of class :name= Lao Wang
Demo2 Instance properties of class :age=20
Demo2 Instance properties of class :name= Lao Wang
Demo2 Instance properties of class :age=20
cl1 The memory address of the instance :1842280993096
cl2 The memory address of the instance :1842280993096
cl1 Whether it is cl2 True

A little help

Finally, thank everyone who reads my article carefully , Watching the rise and attention of fans all the way , Reciprocity is always necessary , Although it's not very valuable , If you can use it, you can take it !

The house needs to be built layer by layer , Knowledge needs to be learned at one point one . We should lay a good foundation in the process of learning , More hands-on practice , Don't talk much , The last dry goods here ! I stayed up late to sort out the stages ( function 、 Interface 、 automation 、 performance 、 Test open ) Skills learning materials + Practical explanation , Very suitable for studying in private , It's much more efficient than self-study , Share with you .

Get off w/x/g/z/h: Software testing tips dao

Typing is not easy , If this article is helpful to you , Click a like, collect a hide and pay attention , Give the author an encouragement . It's also convenient for you to find it quickly next time .


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