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
    
    
  • 相关阅读:
    论面向服务架构及其应用
    一线架构师实践指南阅读笔记03
    一线架构师实践指南阅读笔记02
    一线架构师实践指南Refined Architecture阶段阅读笔记01
    TortoiseGit无法勾选Load Putty Key,该选项为灰色的解决办法
    maya 2015配置openCollada插件
    阿里云ubuntu搭建SVN服务器
    Ventuz配置Leap Motion环境
    Android中将Bitmap对象以PNG格式保存在内部存储中
    Android Studio使用OpenCV后,使APP不安装OpenCV Manager即可运行
  • 原文地址:https://www.cnblogs.com/maxiaohei/p/7810613.html
Copyright © 2011-2022 走看看