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
    
    
  • 相关阅读:
    UVA 11488 Hyper Prefix Sets (字典树)
    UVALive 3295 Counting Triangles
    POJ 2752 Seek the Name, Seek the Fame (KMP)
    UVA 11584 Partitioning by Palindromes (字符串区间dp)
    UVA 11100 The Trip, 2007 (贪心)
    JXNU暑期选拔赛
    计蒜客---N的-2进制表示
    计蒜客---线段的总长
    计蒜客---最大质因数
    JustOj 2009: P1016 (dp)
  • 原文地址:https://www.cnblogs.com/maxiaohei/p/7810613.html
Copyright © 2011-2022 走看看