Python----面向對象---元類介紹
阿新 • • 發佈:2018-03-27
attr pen .html ash 實例 package clas Python全棧 reference
一、儲備知識exec
參數1:字符串形式的命令
參數2:全局作用域(字典形式),如果不指定默認就使用globals()
參數3:局部作用域(字典形式),如果不指定默認使用locals()
示例代碼如下:
1 g = { 2 ‘x‘: 1, 3 ‘y‘: 2 4 } 5 6 l = {} 7 8 exec(‘‘‘ 9 global x, m 10 x = 10 11 m = 100 12 13 z = 3 14 ‘‘‘, g, l) 15 16 print(g) 17 print(l) 18 19 結果為: 20 21 {‘x‘: 10, ‘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-infunction 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. 22 All Rights Reserved. 23 24 Copyright (c) 2000 BeOpen.com. 25 All Rights Reserved. 26 27 Copyright (c) 1995-2001 Corporation for National Research Initiatives. 28 All Rights Reserved. 29 30 Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam. 31 All Rights Reserved., ‘credits‘: Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands 32 for supporting Python development. See www.python.org for more information., ‘license‘: See http://www.python.org/3.6/license.html, ‘help‘: Type help() for interactive help, or help(object) for help about object.}, ‘m‘: 100} 33 {‘z‘: 3}
l為局部變量,執行後會增加z的鍵值對,g為全局變量,x的值會修改為10,m不存在,會添加進g
python中一切皆對象,對象可以怎麽用?
1、都可以被引用, x=obj
2、都可以當做函數的參數傳入
3、都可以當做函數的返回值
4、都可以當做容器的元素, l = [func, time, obj, 1]
類也是對象,那他是由什麽實例化而來的呢:
1 class Foo: 2 pass 3 4 obj = Foo() 5 print(type(obj)) 6 print(type(Foo)) 7 8 結果為: 9 10 <class ‘__main__.Foo‘> 11 <class ‘type‘>
可見,Foo類是由type類實例化而來,
1 class Bar: 2 pass 3 4 5 print(type(Bar)) 6 7 結果為: 8 9 <class ‘type‘>
產生類的類稱之為元類,默認所有使用class定義的類,他們的元類是type
定義類的兩中方式:
方式一:class
1 class Chinese: # Chinese = type(...) 2 country = ‘China‘ 3 4 def __init__(self, name, age): 5 self.name = name 6 self.age = age 7 8 def talk(self): 9 print(‘%s is talking ‘ % self.name)
方式二:type
定義類的三要素: 類名, 類的基類們, 類的名稱空間
1 class_name = ‘Chinese‘ 2 class_bases = (object, ) 3 4 class_body = """ 5 country = ‘China‘ 6 7 def __init__(self, name, age): 8 self.name = name 9 self.age = age 10 11 def talk(self): 12 print(‘%s is talking ‘ % self.name) 13 """ 14 15 class_dic = {} 16 17 exec(class_body, globals(), class_dic) 18 print(globals()) 19 print(class_dic) 20 21 chinese1 = type(class_name, class_bases, class_dic) 22 print(chinese1) 23 24 結果為: 25 26 {‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘__package__‘: None, ‘__loader__‘: <_frozen_importlib_external.SourceFileLoader object at 0x0000026F4279D7F0>, ‘__spec__‘: None, ‘__annotations__‘: {}, ‘__builtins__‘: <module ‘builtins‘ (built-in)>, ‘__file__‘: ‘C:/Users/xu516/PycharmProjects/Python全棧開發/第三模塊/面向對象編程/26 元類介紹.py‘, ‘__cached__‘: None, ‘class_name‘: ‘Chinese‘, ‘class_bases‘: (<class ‘object‘>,), ‘class_body‘: "\ncountry = ‘China‘\n\ndef __init__(self, name, age):\n self.name = name\n self.age = age\n\ndef talk(self):\n print(‘%s is talking ‘ % self.name)\n", ‘class_dic‘: {‘country‘: ‘China‘, ‘__init__‘: <function __init__ at 0x0000026F42793510>, ‘talk‘: <function talk at 0x0000026F42A1B620>}} 27 {‘country‘: ‘China‘, ‘__init__‘: <function __init__ at 0x0000026F42793510>, ‘talk‘: <function talk at 0x0000026F42A1B620>} 28 <class ‘__main__.Chinese‘>
type實例化生成chinese1類,
1 obj1 = chinese1(‘egon‘, 88) 2 print(obj1, obj1.name, obj1.age) 3 4 結果為: 5 6 <__main__.Chinese object at 0x0000013E2417B518> egon 88
type類實例化生成的chinese1類,
Python----面向對象---元類介紹