zoukankan      html  css  js  c++  java
  • exec()和元类

    一、exec()的作用

    exec执行储存在字符串或文件中的 Python 语句,相比于 eval,exec可以执行更复杂的 Python 代码,

    语法:

    exec(code,global_dict,local_dict)

    code:传入的文本代码

    global_dic:传入的字典,接收的是全局名称空间和内置名称空间

    local_dict:传入的字典,接收局部名称空间

    例子

    code = '''
    global x
    x = 10
    y = 20
    '''
    global_dict = {'x':200}
    
    local_dict = {}
    
    exec(code,global_dict,local_dict)
    
    print(global_dict)
    #global_dict返回全局名称空间和内置名称空间
    
    print(local_dict)
    #local_dict返回局部名称空间
    
    {'x': 10, '__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.
    All Rights Reserved.
    
    Copyright (c) 2000 BeOpen.com.
    All Rights Reserved.
    
    Copyright (c) 1995-2001 Corporation for National Research Initiatives.
    All Rights Reserved.
    
    Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
    All Rights Reserved., 'credits':     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
        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.}}
    {'y': 20}
    

    二、元类

    2.1什么是元类,元类的作用是什么?

    在Python当中万物皆对象,我们用class关键字定义的类本身也是一个对象,负责产生该对象的类称之为元类,元类可以简称为类的类。元类的主要目的是为了控制类的创建行为。

    type是Python的一个内建元类,用来直接控制生成类,在python当中任何class定义的类其实都是type类实例化的结果。

    只有继承了type类才能称之为一个元类,否则就是一个普通的自定义类,自定义元类可以控制类的产生过程,类的产生过程其实就是元类的调用过程。

    2.2自定义创建元类

    1. 自定义一个类,继承type类,派生出自己的属性和方法

    2. 需要使用元类的类通过metaclass指定自定义好的元类。

    3. 继承type类规定的三个参数:

      a. what: 类名 --> type对象的名称

      b. bases: --> 基类/父类

      c. dict: --> 类的名称空间

    例子

    控制类的定义

    class MyMeta(type):
    #控制类的定义
        def __init__(self,class_name,class_base,class_dict):
    
            print(class_name)
    
            if not class_name.istitle():
                raise TypeError('类的首字母必须大写')
    
            if not class_dict.get('__doc__'):
                raise TypeError('类内部必须要写注释')
    
            print(class_base)
            print(class_dict)
    
            super().__init__(class_name,class_base,class_dict)
            #继承type类需要传入的三个参数
    
    class Bar():
        pass
    
    class Foo(Bar,metaclass=MyMeta):# MyMeta(Foo, Foo_name, (Bar, ), foo_dict)
        'metaclass=MyMeta会将元类需要的参数都传给元类'
        x = 10
        def __init__(self,y,z):
            self.y = y
            self.z = z
    
        def f1(self):
            print('from Foo.f1')
    
    foo = Foo(20,30)
    
    (<class '__main__.Bar'>,)
    {'__module__': '__main__', '__qualname__': 'Foo', '__doc__': 'metaclass=MyMeta会将元类需要的参数都传给元类', 'x': 10, '__init__': <function Foo.__init__ at 0x000001D8048F0F28>, 'f1': <function Foo.f1 at 0x000001D804902048>}
    

    控制类的调用方式

    当调用类时会先触发类内部或者类继承的类内部的__call__,然后通过__call__调用__new__

    实例化一个空对象,实现类的调用方式的控制只需要在类内部直接使用这两个方法。

     # 模拟type元类内部做的事情
        # 元类触发的__call__可以控制类的调用。调用__call__会触发以下两点
        def __call__(self, *args, **kwargs):
            # 1.会调用__new__()实例化一个空obj
            obj = object.__new__(self)
            # 2.会执行__init__(obj, *args, **kwargs),
            obj.__init__(*args, **kwargs)
            return obj
    
        # 可以通过元类内部的__new__控制对象的创建
        def __new__(cls, *args, **kwargs):
            pass
    
  • 相关阅读:
    Java Nashorn--Part 4
    Java Nashorn--Part 3
    Java Nashorn--Part 2
    Java Nashorn--Part 1
    Java 异步 IO
    代码天天写,快乐天天有!
    比迷路更可怕的,是对读书的迷失。
    《寄生兽》观后感
    浅谈生活
    8月份的尾巴
  • 原文地址:https://www.cnblogs.com/ghylpb/p/11794518.html
Copyright © 2011-2022 走看看