面向对象之元类
一、元类的介绍
1、知识储备--了解exec
# exec
'''
参数一:字符串形式的命令
参数二:全局作用域(字典形式),如果不指定默认就使用globals()
参数三:局部作用域(字典形式),如果不指定默认就使用locals()
'''
1.1、示例:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
g = {'a':6, 'b':8}
l = {}
exec('''
global a,i
a = 66
i = 99
y = 100
''',g,l)
print(g)
# {'a': 66, 'b': 8, '__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.
print(l) # {'y': 100}
2、Python中一切皆对象,对象有哪些用法?
1、都可以被引用
2、都可以当作函数的参数传入
3、都可以当作函数的返回值
4、都可以当作容器类的元素(所谓容器就是可以盛放一连串元素的类型,如列表字典元组集合等)
3、类也是对象,产生类的类称之为元类,默认所有用class定义的类,他们的元类是type
class Func:
pass
obj = Func()
print(type(obj)) # <class '__main__.Func'>
print(type(Func)) # <class 'type'>
class Bar:
pass
print(type(Bar)) # <class 'type'>
4、定义类的两种方式
4.1 方式一:class关键字
示例:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Chinese1:
country = 'China'
def __init__(self,name,age):
self.name = name
self.age = age
def chat(self):
print('%s is chating now'%self.name)
print(Chinese1) # <class '__main__.Chinese1'>
obj1 = Chinese1('cc',21)
print(obj1,obj1.name,obj1.age) # <__main__.Chinese1 object at 0x00000240924237B8> cc 21
4.2 方式二:type
定义类的三要素:类名,类的基类,类的名称空间
示例:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class_name = 'Chinese2'
class_bases = (object,)
class_body='''
country='China'
def __init__(self,name,age):
self.name = name
self.age = age
def chat(self):
print('%s is chating now'%self.name)
'''
class_dic = {}
exec(class_body,globals(),class_dic)
print(class_dic)
# {'country': 'China', '__init__': <function __init__ at 0x0000020683338F28>, 'chat': <function chat at 0x000002068335B048>}
Chinese2 = type(class_name,class_bases,class_dic)
print(Chinese2)
obj2 = Chinese2('cc',21)
print(obj2,obj2.name,obj2.age) # <__main__.Chinese2 object at 0x0000024092423320> cc 21
二、自定义元类以控制类的创建行为
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Mymeta(type):
def __init__(self,class_name,class_bases,class_dic):
# print(class_name) # Chinese
# print(class_bases) # (<class 'object'>,)
# print(class_dic)
if not class_name.istitle():
raise TypeError('类名首字母应大写!')
if not '__doc__' or not class_dic['__doc__'].strip():
raise TypeError('必须加注释')
super(Mymeta,self).__init__(class_name,class_bases,class_dic) # 重用父类中的方法
class Chinese(object,metaclass=Mymeta): # metaclass= 表示指定元类
'''
由元类Mymeta控制类的创建行为
'''
country = 'China'
def __init__(self,name,age):
self.name = name
self.age = age
def chat(self):
print('%s is chating now'%self.name)
#Chinese = Mymeta(class_name,class_bases,class_dic)
三、自定义元类控制类的实例化
1、前情提要
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# __call__方法
class Func:
def __call__(self, *args, **kwargs):
print(self)
print(args) # (1, 2, 3, 4)
print(kwargs) # {'a': 3}
obj = Func()
obj(1,2,3,4,a=3) # 调用对象,会触发__call__方法,把对象本身和参数传入__call__方法中存成元祖和字典
# 元类内部也应该有一个__call__方法,会在调用Func时触发执行
# 如 Func(1,2,a=5) --> Func.__call__(Func,1,2,a=5)
2、示例:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
# write by congcong
class Mymeta(type):
def __init__(self,class_name,class_bases,class_dic):
# print(class_name) # Chinese
# print(class_bases) # (<class 'object'>,)
# print(class_dic)
if not class_name.istitle():
raise TypeError('类名首字母应大写!')
if not '__doc__' or not class_dic['__doc__'].strip():
raise TypeError('必须加注释')
super(Mymeta,self).__init__(class_name,class_bases,class_dic) # 重用父类中的方法
def __call__(self, *args, **kwargs):
'''
# print(self) # <class '__main__.Chinese'>
# print(args) # ('cc',)
# print(kwargs) # {'age': 21}'''
# 第一件事:先造一个空对象
obj = object.__new__(self)
# 第二件事:初始化对象
self.__init__(obj,*args,**kwargs)
# 第三件事:返回对象
return obj
class Chinese(object,metaclass=Mymeta): # metaclass= 表示指定元类
'''
由元类Mymeta控制类的实例化行为
'''
country = 'China'
def __init__(self,name,age):
self.name = name
self.age = age
def chat(self):
print('%s is chating now'%self.name)
四、自定义元类控制类的实例化应用
单例模式
1、实现方式一
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
# write by congcong
class Mysql:
__instance = None
def __init__(self):
self.host = '127.0.0.1'
self.port = 3306
@classmethod
def singleton(cls):
if not cls.__instance:
obj = cls()
cls.__instance = obj
return cls.__instance
# obj1 = Mysql()
# obj2 = Mysql()
# obj3 = Mysql()
# print(obj1) # <__main__.Mysql object at 0x0000029CEF267EB8>
# print(obj2) # <__main__.Mysql object at 0x0000029CEF273080>
# print(obj3) # <__main__.Mysql object at 0x0000029CEF273128>
# 这种实例化方式十分浪费内存,下列方式仅占用一份内存
obj1 = Mysql.singleton()
obj2 = Mysql.singleton()
obj3 = Mysql.singleton()
print(obj1) # <__main__.Mysql object at 0x00000243FC8B7EB8>
print(obj2) # None
print(obj3) # None
2、实现方式二(元类的方式)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
class Mymeta(type):
def __init__(self,class_name,class_bases,class_dic):
# print(class_name) # Chinese
# print(class_bases) # (<class 'object'>,)
# print(class_dic)
if not class_name.istitle():
raise TypeError('类名首字母应大写!')
if not '__doc__' or not class_dic['__doc__'].strip():
raise TypeError('必须加注释')
super(Mymeta,self).__init__(class_name,class_bases,class_dic) # 重用父类中的方法
self.__instance = None
def __call__(self, *args, **kwargs):
if not self.__instance:
obj = object.__new__(self) # 造一个空对象
self.__init__(obj) # 实例化
self.__instance = obj # 赋值,更改属性
return self.__instance # 返回
class Mysql(object,metaclass=Mymeta):
'''
自定义元类控制类的实例化
'''
__instance = None
def __init__(self):
self.host = '127.0.0.1'
self.port = 3306
obj1 = Mysql()
obj2= Mysql()
obj3 = Mysql()
print(obj1==obj2==obj3) # True
读书原为修身,正己才能正人正世;不修身不正己而去正人正世者,无一不是盗名欺世;你把念过的书能用上十之一二,就是很了不得的人了。——朱先生