• import和可调用对象的实现原理


    import 模块名

    模块名没有使用字符串的原因是,被赋值给一个同名的变量,利用变量导入模块

     用途:

    在自己写的代码中调用自己的包,可以用 __import__ 导入

    In [1]: import time
    
    In [2]: print(time.ctime())
    Thu Nov  9 17:32:54 2017
    
    In [3]: ti = __import__('time')
    
    In [4]: print(ti.ctime())
    Thu Nov  9 17:33:34 2017

    一个对象是否可以调用的判断方法, callable(对象名) ,可以调用返回true, 否则返回 false

    In [18]: fun()
    aah
    
    In [19]: callable(fun)
    Out[19]: True
    
    In [20]: dir(fun)
    Out[20]:
    ['__annotations__',
     '__call__',
     '__class__',
     '__closure__',
     '__code__',
     '__defaults__',
     '__delattr__',
     '__dict__',
     '__dir__',
     '__doc__',
     '__eq__',
     '__format__',
     '__ge__',
     '__get__',
     '__getattribute__',
     '__globals__',
     '__gt__',
     '__hash__',
     '__init__',
     '__init_subclass__',
     '__kwdefaults__',
     '__le__',
     '__lt__',
     '__module__',
     '__name__',
     '__ne__',
     '__new__',
     '__qualname__',
     '__reduce__',
     '__reduce_ex__',
     '__repr__',
     '__setattr__',
     '__sizeof__',
     '__str__',
     '__subclasshook__']

    被本身默认为不可调用对象,将类变成可调用对象的方法是在类中重写  __call__ 方法:

    In [21]: class obj1():
        ...:     pass
        ...:
    
    In [22]: o1 = obj1()
    
    In [23]: o1()
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-23-188e6fb838ce> in <module>()
    ----> 1 o1()
    
    TypeError: 'obj1' object is not callable
    In [28]: callable(o1)
    Out[28]: False
     
    In [21]: class obj1():
        ...:     pass
        ...:
    
    In [22]: o1 = obj1()
    
    In [23]: o1()
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-23-188e6fb838ce> in <module>()
    ----> 1 o1()
    
    TypeError: 'obj1' object is not callable
    
    In [24]: class obj2():
        ...:     def __call__(self):
        ...:         print('rewirte')
        ...:
    
    In [25]: o2=obj2()
    
    In [26]: o2()
    rewirte
    
    In [27]: callable(o2)
    Out[27]: True
    
    
  • 相关阅读:
    工具进阶:如何利用 MAT 找到问题发生的根本原因
    性能优化步骤
    搞定内存泄漏
    jvm配置示例
    vue的transition相同元素通过v-if,以及绑定key的区别
    安装nvm之node版本管理器
    在ts中定义变量类型的dva使用方法
    dva的全部用法
    react父子组件传值之二,ref传值(父组件调用子组件的值和方法) useRef+useImperativeHandle(hook)
    react父子组件传值方式一之props方法
  • 原文地址:https://www.cnblogs.com/maxiaohei/p/7810613.html
Copyright © 2020-2023  润新知