zoukankan      html  css  js  c++  java
  • Python----面向对象---元类介绍

    一、储备知识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.
    
    Noteworthy: 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.
    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': "
    country = 'China'
    
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def talk(self):
        print('%s is talking ' % self.name)
    ", '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类,

  • 相关阅读:
    7-22 朋友圈(25 分)
    c++之函数重载
    c++之函数的其它用法
    c++之引用
    c++之内存模型
    c++实例之通讯录管理系统之清空联系人功能(七)
    c++实例之通讯录管理系统之修改联系人功能(六)
    c++实例之通讯录管理系统之查找联系人功能(五)
    c++实例之通讯录管理系统之删除联系人功能(四)
    c++实例之通讯录管理系统之显示联系人功能(三)
  • 原文地址:https://www.cnblogs.com/xudachen/p/8660167.html
Copyright © 2011-2022 走看看