zoukankan      html  css  js  c++  java
  • 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
    
    
  • 相关阅读:
    深度排序与alpha混合 【转】
    SVN服务器配置说明 【转】
    3D空间中射线与轴向包围盒AABB的交叉检测算法 【转】
    Linux系统管理员不可不知的命令:sudo
    Linux 系统实时监控的瑞士军刀 —— Glances
    shell定期转移日志文件到云盘并定期删除云盘文件
    zabbix监控第二块网卡是否连通
    Gitlab自动触发Jenkins构建打包
    shell脚本检测网络是否畅通
    Prometheus入门
  • 原文地址:https://www.cnblogs.com/maxiaohei/p/7810613.html
Copyright © 2011-2022 走看看