面向对象——元类

Posted GraceZen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了面向对象——元类相关的知识,希望对你有一定的参考价值。

1.exec

技术分享图片
1 exec(source, globals=None, locals=None, /)
2     Execute the given source in the context of globals and locals.
3     
4     The source may be a string representing one or more Python statements
5     or a code object as returned by compile().
6     The globals must be a dictionary and locals can be any mapping,
7     defaulting to the current globals and locals.
8     If only globals is given, locals defaults to it.
exec语法
  • 参数一:字符串形式的命令
  • 参数二:全局作用域(字典形式),如果不指定,默认为globals()
  • 参数三:局部作用域(字典形式),如果不指定,默认为locals()
技术分享图片
 1 s = """
 2 global x,z
 3 x = 100
 4 z = 200
 5 
 6 m = 300
 7 """
 8 g = {x:1,y:2}
 9 l = {}
10 exec(s,g,l)
11 # print(g)
12 #{‘x‘: 100, ‘y‘: 2, ‘__builtins__‘: {‘__name__‘: ‘builtins‘, ‘__doc__‘: "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil‘ object; Ellipsis represents `...‘ in slices.", ‘__package__‘: ‘‘, ‘__loader__‘: <class ‘_frozen_importlib.BuiltinImporter‘>, ‘__spec__‘: ModuleSpec(name=‘builtins‘, loader=<class ‘_frozen_importlib.BuiltinImporter‘>), ‘__build_class__‘: <built-in function __build_class__>, ‘__import__‘: <built-in function __import__>, ‘abs‘: <built-in function abs>, ‘all‘: <built-in function all>, ‘any‘: <built-in function any>, ‘ascii‘: <built-in function ascii>, ‘bin‘: <built-in function bin>, ‘callable‘: <built-in function callable>, ‘chr‘: <built-in function chr>, ‘compile‘: <built-in function compile>, ‘delattr‘: <built-in function delattr>, ‘dir‘: <built-in function dir>, ‘divmod‘: <built-in function divmod>, ‘eval‘: <built-in function eval>, ‘exec‘: <built-in function exec>, ‘format‘: <built-in function format>, ‘getattr‘: <built-in function getattr>, ‘globals‘: <built-in function globals>, ‘hasattr‘: <built-in function hasattr>, ‘hash‘: <built-in function hash>, ‘hex‘: <built-in function hex>, ‘id‘: <built-in function id>, ‘input‘: <built-in function input>, ‘isinstance‘: <built-in function isinstance>, ‘issubclass‘: <built-in function issubclass>, ‘iter‘: <built-in function iter>, ‘len‘: <built-in function len>, ‘locals‘: <built-in function locals>, ‘max‘: <built-in function max>, ‘min‘: <built-in function min>, ‘next‘: <built-in function next>, ‘oct‘: <built-in function oct>, ‘ord‘: <built-in function ord>, ‘pow‘: <built-in function pow>, ‘print‘: <built-in function print>, ‘repr‘: <built-in function repr>, ‘round‘: <built-in function round>, ‘setattr‘: <built-in function setattr>, ‘sorted‘: <built-in function sorted>, ‘sum‘: <built-in function sum>, ‘vars‘: <built-in function vars>, ‘None‘: None, ‘Ellipsis‘: Ellipsis, ‘NotImplemented‘: NotImplemented, ‘False‘: False, ‘True‘: True, ‘bool‘: <class ‘bool‘>, ‘memoryview‘: <class ‘memoryview‘>, ‘bytearray‘: <class ‘bytearray‘>, ‘bytes‘: <class ‘bytes‘>, ‘classmethod‘: <class ‘classmethod‘>, ‘complex‘: <class ‘complex‘>, ‘dict‘: <class ‘dict‘>, ‘enumerate‘: <class ‘enumerate‘>, ‘filter‘: <class ‘filter‘>, ‘float‘: <class ‘float‘>, ‘frozenset‘: <class ‘frozenset‘>, ‘property‘: <class ‘property‘>, ‘int‘: <class ‘int‘>, ‘list‘: <class ‘list‘>, ‘map‘: <class ‘map‘>, ‘object‘: <class ‘object‘>, ‘range‘: <class ‘range‘>, ‘reversed‘: <class ‘reversed‘>, ‘set‘: <class ‘set‘>, ‘slice‘: <class ‘slice‘>, ‘staticmethod‘: <class ‘staticmethod‘>, ‘str‘: <class ‘str‘>, ‘super‘: <class ‘super‘>, ‘tuple‘: <class ‘tuple‘>, ‘type‘: <class ‘type‘>, ‘zip‘: <class ‘zip‘>, ‘__debug__‘: True, ‘BaseException‘: <class ‘BaseException‘>, ‘Exception‘: <class ‘Exception‘>, ‘TypeError‘: <class ‘TypeError‘>, ‘StopAsyncIteration‘: <class ‘StopAsyncIteration‘>, ‘StopIteration‘: <class ‘StopIteration‘>, ‘GeneratorExit‘: <class ‘GeneratorExit‘>, ‘SystemExit‘: <class ‘SystemExit‘>, ‘KeyboardInterrupt‘: <class ‘KeyboardInterrupt‘>, ‘ImportError‘: <class ‘ImportError‘>, ‘ModuleNotFoundError‘: <class ‘ModuleNotFoundError‘>, ‘OSError‘: <class ‘OSError‘>, ‘EnvironmentError‘: <class ‘OSError‘>, ‘IOError‘: <class ‘OSError‘>, ‘WindowsError‘: <class ‘OSError‘>, ‘EOFError‘: <class ‘EOFError‘>, ‘RuntimeError‘: <class ‘RuntimeError‘>, ‘RecursionError‘: <class ‘RecursionError‘>, ‘NotImplementedError‘: <class ‘NotImplementedError‘>, ‘NameError‘: <class ‘NameError‘>, ‘UnboundLocalError‘: <class ‘UnboundLocalError‘>, ‘AttributeError‘: <class ‘AttributeError‘>, ‘SyntaxError‘: <class ‘SyntaxError‘>, ‘IndentationError‘: <class ‘IndentationError‘>, ‘TabError‘: <class ‘TabError‘>, ‘LookupError‘: <class ‘LookupError‘>, ‘IndexError‘: <class ‘IndexError‘>, ‘KeyError‘: <class ‘KeyError‘>, ‘ValueError‘: <class ‘ValueError‘>, ‘UnicodeError‘: <class ‘UnicodeError‘>, ‘UnicodeEncodeError‘: <class ‘UnicodeEncodeError‘>, ‘UnicodeDecodeError‘: <class ‘UnicodeDecodeError‘>, ‘UnicodeTranslateError‘: <class ‘UnicodeTranslateError‘>, ‘AssertionError‘: <class ‘AssertionError‘>, ‘ArithmeticError‘: <class ‘ArithmeticError‘>, ‘FloatingPointError‘: <class ‘FloatingPointError‘>, ‘OverflowError‘: <class ‘OverflowError‘>, ‘ZeroDivisionError‘: <class ‘ZeroDivisionError‘>, ‘SystemError‘: <class ‘SystemError‘>, ‘ReferenceError‘: <class ‘ReferenceError‘>, ‘BufferError‘: <class ‘BufferError‘>, ‘MemoryError‘: <class ‘MemoryError‘>, ‘Warning‘: <class ‘Warning‘>, ‘UserWarning‘: <class ‘UserWarning‘>, ‘DeprecationWarning‘: <class ‘DeprecationWarning‘>, ‘PendingDeprecationWarning‘: <class ‘PendingDeprecationWarning‘>, ‘SyntaxWarning‘: <class ‘SyntaxWarning‘>, ‘RuntimeWarning‘: <class ‘RuntimeWarning‘>, ‘FutureWarning‘: <class ‘FutureWarning‘>, ‘ImportWarning‘: <class ‘ImportWarning‘>, ‘UnicodeWarning‘: <class ‘UnicodeWarning‘>, ‘BytesWarning‘: <class ‘BytesWarning‘>, ‘ResourceWarning‘: <class ‘ResourceWarning‘>, ‘ConnectionError‘: <class ‘ConnectionError‘>, ‘BlockingIOError‘: <class ‘BlockingIOError‘>, ‘BrokenPipeError‘: <class ‘BrokenPipeError‘>, ‘ChildProcessError‘: <class ‘ChildProcessError‘>, ‘ConnectionAbortedError‘: <class ‘ConnectionAbortedError‘>, ‘ConnectionRefusedError‘: <class ‘ConnectionRefusedError‘>, ‘ConnectionResetError‘: <class ‘ConnectionResetError‘>, ‘FileExistsError‘: <class ‘FileExistsError‘>, ‘FileNotFoundError‘: <class ‘FileNotFoundError‘>, ‘IsADirectoryError‘: <class ‘IsADirectoryError‘>, ‘NotADirectoryError‘: <class ‘NotADirectoryError‘>, ‘InterruptedError‘: <class ‘InterruptedError‘>, ‘PermissionError‘: <class ‘PermissionError‘>, ‘ProcessLookupError‘: <class ‘ProcessLookupError‘>, ‘TimeoutError‘: <class ‘TimeoutError‘>, ‘open‘: <built-in function open>, ‘quit‘: Use quit() or Ctrl-Z plus Return to exit, ‘exit‘: Use exit() or Ctrl-Z plus Return to exit, ‘copyright‘: Copyright (c) 2001-2017 Python Software Foundation.
13 # All Rights Reserved.
14 #
15 # Copyright (c) 2000 BeOpen.com.
16 # All Rights Reserved.
17 #
18 # Copyright (c) 1995-2001 Corporation for National Research Initiatives.
19 # All Rights Reserved.
20 #
21 # Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
22 # All Rights Reserved., ‘credits‘:     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
23 #     for supporting Python development.  See www.python.org for more information., ‘license‘: Type license() to see the full license text, ‘help‘: Type help() for interactive help, or help(object) for help about object.}, ‘z‘: 200}
24 
25 print(l)
26 #{‘m‘: 300}
exec示例

2.类也是对象

  • python中一切皆对象,类本身也是一个对象,可以将类当作一个对象去使用,同样满足第一类对象的概念
    • 把类赋值给一个变量
    • 把类作为函数参数进行传递
    • 把类作为函数的返回值
    • 在运行时动态地创建类
  • 1 class Foo:
    2     pass
    3 f1 = Foo()#f1是通过Foo类实例化的对象
    4 print(type(f1))#<class ‘__main__.Foo‘>
    5 print(type(Foo))#<class ‘type‘>  类(对象)Foo是由type类实例化而来

3.元类

  • 元类是类的类,是类的模板
    • 元类是用来控制如何创建类的,正如类是创建对象的模板一样,而元类的主要目的是为了控制类的创建行为
    • 元类的实例化的结果是我们用class 定义的类,正如类的实例为对象(f1对象是Foo类的一个实例,Foo类是type类的一个实例)
    • type是python的一个内建元类,用来直接控制生成类,python中任何class定义的类其实都是type类实例化的对象

4.创建类的两种方式

  • 方式一:使用class关键字
  • 技术分享图片
     1 class Chinese(object):
     2     country=China
     3     def __init__(self,name,age):
     4         self.name=name
     5         self.age=age
     6     def talk(self):
     7         print(%s is talking %self.name)
     8 # print(Chinese.__dict__)
     9 # {‘country‘: ‘China‘, ‘__init__‘: <function __init__ at 0x0000000002062E18>, ‘talk‘: <function talk at 0x00000000021D4048>,...}
    10 # print(Chinese)
    11 # <class ‘__main__.Chinese‘>
    View Code
  • 方式二:手动模拟class创建类的过程:将创建类的步骤拆分开,手动去创建
  • 技术分享图片
     1 #创建类的步骤
     2 #1.类名
     3 #2.类的父类,默认是object
     4 #3.类体
     5 
     6 #1.类名
     7 class_name = Chinese
     8 #2.类的父类,默认是object
     9 class_bases = (object,)
    10 #3.类体
    11 class_body = """
    12 country=‘China‘
    13 def __init__(self,name,age):
    14     self.name=name
    15     self.age=age
    16 def talk(self):
    17     print(‘%s is talking‘ %self.name)
    18 """
    19 #步骤一:把类体 -> 名称空间:类体定义的名字都会存放于类的名称空间中(一个局部的名称空间),
    20 #       我们可以事先定义好一个空字典,然后用exec去执行类体的代码(exec产生名称空间的过程
    21 #       与真正的class过程类似,只是后者会将__开头的属性变形),生成类的局部名称空间,即填充字典
    22 class_dic = {}
    23 exec(class_body,globals(),class_dic)
    24 # print(class_dic)
    25 #{‘country‘: ‘China‘, ‘__init__‘: <function __init__ at 0x00000000004D2E18>, ‘talk‘: <function talk at 0x00000000028A4048>}
    26 
    27 #步骤二:调用元类type(也可以自定义)来产生类Chinese
    28 #       定义类的三要素:类名,类的基类们,类的名称空间
    29 Chinese = type(class_name,class_bases,class_dic)
    30 # print(Chinese.__dict__)
    31 # {‘country‘: ‘China‘, ‘__init__‘: <function __init__ at 0x0000000002062E18>, ‘talk‘: <function talk at 0x00000000021D4048>,...}
    32 # print(Chinese)
    33 #<class ‘__main__.Chinese‘>
    34 obj = Chinese(egon,18)
    35 # print(obj)
    36 # <__main__.Chinese object at 0x000000000216AE80>
    37 # print(obj.__dict__)
    38 # {‘name‘: ‘egon‘, ‘age‘: 18}
    View Code

5.自定义元类控制类的行为

  • 一个类没有声明自己的元类,默认他的元类就是type,除了使用元类type,用户也可以通过继承type来自定义元类
  • 技术分享图片
     1 #!!!如果你拷贝不注明出处的话,以后老子都不写了!!!
     2 #知识储备:
     3     #产生的新对象 = object.__new__(继承object类的子类)
     4 #步骤一:如果说People=type(类名,类的父类们,类的名称空间),那么我们定义元类如下,来控制类的创建
     5 class Mymeta(type):  # 继承默认元类的一堆属性
     6     def __init__(self, class_name, class_bases, class_dic):
     7         if __doc__ not in class_dic or not class_dic.get(__doc__).strip():
     8             raise TypeError(必须为类指定文档注释)
     9         if not class_name.istitle():
    10             raise TypeError(类名首字母必须大写)
    11         super(Mymeta, self).__init__(class_name, class_bases, class_dic)
    12 class Chinese(object, metaclass=Mymeta):#metaclass=Mymeta不写这个的话,默认为type
    13     """
    14     ....
    15     """
    16     country = China
    17     def __init__(self, name, age):
    18         self.name = name
    19         self.age = age
    20     def talk(self):
    21         print(%s is talking % self.name)
    步骤一
  • 技术分享图片
     1 #知识储备:__call__方法
     2 # class Foo:
     3 #         pass
     4 # obj=Foo()
     5 # obj()#报错,‘Foo‘ object is not callable
     6 class Foo:
     7     def __init__(self, name, age):
     8         self.name = name
     9         self.age = age
    10     def __call__(self, *args, **kwargs):
    11         print(self)
    12         print(args)
    13         print(kwargs)
    14 obj=Foo()
    15 # obj()#对象在调用时会触发obj.__call__(obj, *args, **kwargs)
    16 # <__main__.Foo object at 0x00000000022EA240>
    17 # ()
    18 # {}
    19 obj(1,2,3,a = 1,b = 2,c = 3)#obj.__call__(obj,1,2,3,a = 1,b = 2,c = 3)
    20 # <__main__.Foo object at 0x00000000021BA240>
    21 # (1, 2, 3)
    22 # {‘a‘: 1, ‘b‘: 2, ‘c‘: 3}
    步骤二
    技术分享图片
     1 class Mymeta(type):  # 继承默认元类的一堆属性
     2     def __init__(self, class_name, class_bases, class_dic):
     3         if __doc__ not in class_dic or not class_dic.get(__doc__).strip():
     4             raise TypeError(必须为类指定文档注释)
     5         if not class_name.istitle():
     6             raise TypeError(类名首字母必须大写)
     7         super(Mymeta, self).__init__(class_name, class_bases, class_dic)
     8     def __call__(self, *args, **kwargs):
     9         # print(self)
    10         # print(args)
    11         # print(kwargs)
    12         #第一件事:先造一个空对象obj
    13         obj = object.__new__(self)
    14         #第二件事:初始化obj
    15         self.__init__(obj, *args, **kwargs)
    16         #第三件事:返回obj
    17         return obj
    18 class Chinese(object, metaclass=Mymeta):#metaclass=Mymeta不写这个的话,默认为type
    19     """   ...."""
    20     country = China
    21     def __init__(self, name, age):
    22         self.name = name
    23         self.age = age
    24     def talk(self):
    25         print(%s is talking % self.name)
    26 obj = Chinese(egon,age = 18)#Chinese.__call__(Chinese,‘egon‘,18)
    27 print(obj.__dict__)
    28 #{‘name‘: ‘egon‘, ‘age‘: 18}
    29 #如果__call__中没有做那三件事的话,执行print(obj.__dict__)是会报错的
    步骤三
    技术分享图片
     1 #单例模式
     2 # class mysql:
     3 #     def __init__(self):
     4 #         self.host = ‘127.0.0.1‘
     5 #         self.port = 3306
     6 # obj1 = MySQL()
     7 # obj2 = MySQL()
     8 # obj3 = MySQL()
     9 # print(id(obj1))#35368464
    10 # print(id(obj2))#35414088
    11 # print(id(obj3))#35414256
    12 class MySQL:
    13     __instance = None
    14     def __init__(self):
    15         self.host = 127.0.0.1
    16         self.port = 3306
    17     @classmethod
    18     def singleton(cls):
    19         if not cls.__instance:
    20             obj = cls()
    21             cls.__instance = obj
    22         return cls.__instance
    23 obj1 = MySQL.singleton()
    24 obj2 = MySQL.singleton()
    25 obj3 = MySQL.singleton()
    26 print(id(obj1))#35434112
    27 print(id(obj2))#35434112
    28 print(id(obj3))#35434112
    单例模式
    技术分享图片
     1 class Mymeta(type):
     2     def __init__(self, class_name, class_bases, class_dic):
     3         if __doc__ not in class_dic or not class_dic.get(__doc__).strip():
     4             raise TypeError(必须为类指定文档注释)
     5         if not class_name.istitle():
     6             raise TypeError(类名首字母必须大写)
     7         super(Mymeta, self).__init__(class_name, class_bases, class_dic)
     8         self.__instance = None
     9     def __call__(self, *args, **kwargs):
    10         if not self.__instance:
    11             obj = object.__new__(self)
    12             self.__init__(obj)
    13             self.__instance = obj
    14         return self.__instance
    15 
    16 class Mysql(object,metaclass=Mymeta):
    17     """...."""
    18     def __init__(self):
    19         self.host = 127.0.0.1
    20         self.port = 3306
    21 
    22 obj1 = Mysql()
    23 obj2 = Mysql()
    24 obj3 = Mysql()
    25 print(obj1 is obj2 is obj3)#True
    26 print(id(obj1))#32006944
    27 print(id(obj2))#32006944
    28 print(id(obj3))#32006944
    步骤五

     

以上是关于面向对象——元类的主要内容,如果未能解决你的问题,请参考以下文章

Python----面向对象---元类介绍

面向对象之元类

python面向对象--元类

python 吐血总结面向对象元类

python 吐血总结面向对象元类

面向对象--元类