<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                # Python 內省 > 原文: [http://zetcode.com/lang/python/introspection/](http://zetcode.com/lang/python/introspection/) 在 Python 教程的這一部分中,我們討論了自省。 內省是一種自我檢查的行為。 在計算機編程中,自省是在運行時確定對象的類型或屬性的能力。 Python 編程語言對自省有很大的支持。 Python 中的所有內容都是一個對象。 Python 中的每個對象都可以具有屬性和方法。 通過使用內省,我們可以動態檢查 Python 對象。 ## Python `dir`函數 `dir()`函數返回屬于對象的屬性和方法的排序列表。 ```py >>> dir(()) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index'] ``` 在這里,我們看到了元組對象的`dir()`函數的輸出。 ```py >>> print(().__doc__) tuple() -> empty tuple tuple(iterable) -> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object. ``` 我們的研究表明,元組對象有一個`__doc__`屬性。 `direx.py` ```py #!/usr/bin/env python # direx.py import sys class MyObject(object): def __init__(self): pass def examine(self): print(self) o = MyObject() print(dir(o)) print(dir([])) print(dir({})) print(dir(1)) print(dir()) print(dir(len)) print(dir(sys)) print(dir("String")) ``` 該示例使用`dir()`函數檢查了幾個對象:用戶定義的對象,本機數據類型,函數,字符串或數字。 不帶任何參數的`dir()`返回當前作用域中的名稱。 ```py >>> dir() ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__'] >>> import sys >>>import math, os >>> dir() ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'math', 'sys'] ``` 我們在包含一些模塊之前和之后執行`dir()`函數。 ## Python `type()`函數 `type()`函數返回對象的類型。 `typefun.py` ```py #!/usr/bin/env python # typefun.py import sys def function(): pass class MyObject(object): def __init__(self): pass o = MyObject() print(type(1)) print(type("")) print(type([])) print(type({})) print(type(())) print(type(object)) print(type(function)) print(type(MyObject)) print(type(o)) print(type(sys)) ``` 該示例將各種類型的對象打印到控制臺屏幕。 ```py $ ./typefun.py <class 'int'> <class 'str'> <class 'list'> <class 'dict'> <class 'tuple'> <class 'type'> <class 'function'> <class 'type'> <class '__main__.MyObject'> <class 'module'> ``` 這是輸出。 ## `id()`函數 `id()`返回對象的特殊 ID。 `idfun.py` ```py #!/usr/bin/env python # idfun.py import sys def fun(): pass class MyObject(object): def __init__(self): pass o = MyObject() print(id(1)) print(id("")) print(id({})) print(id([])) print(id(sys)) print(id(fun)) print(id(MyObject)) print(id(o)) print(id(object)) ``` 該代碼示例打印內置和自定義的各種對象的 ID。 ```py $ ./idfun.py 10914368 139696088742576 139696087935944 139696065155784 139696088325640 139696088244296 21503992 139696087910776 10738720 ``` ## Python `sys`模塊 `sys`模塊提供對解釋器使用或維護的系統特定變量和函數以及與解釋器強烈交互的函數的訪問。 該模塊允許我們查詢有關 Python 環境的信息。 ```py >>> import sys >>> sys.version '3.5.2 (default, Nov 17 2016, 17:05:23) \n[GCC 5.4.0 20160609]' >>> sys.platform 'linux' >>> sys.path ['', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/home/janbodnar/.local/lib/python3.5/site-packages', '/usr/local/lib/python3.5/dist-packages', '/usr/lib/python3/dist-packages'] ``` 在上面的代碼中,我們檢查了 Python 版本,平臺和搜索路徑位置。 我們還可以使用`dir()`函數來獲取`sys`模塊的變量和函數的完整列表。 ```py >>> sys.executable '/usr/bin/python3' >>> sys.argv [''] >>> sys.byteorder 'little' ``` 該示例顯示了`sys`模塊的`executable`,`argv`和`byteorder`屬性。 ```py >>> sys.executable '/usr/bin/python3' ``` 可執行文件是一個字符串,給出有意義的系統上 Python 解釋器的可執行二進制文件的名稱。 ```py >>> sys.argv [''] ``` 這給出了傳遞給 Python 腳本的命令行參數列表。 ```py >>> sys.byteorder 'little' ``` 字節順序是本機字節順序的指示。 在大端(最高有效字節在前)平臺上,值將為`"big"`,在小端(最低有效字節在前)平臺值將為`"little"`。 ## 其他自省 接下來,我們展示檢查 Python 對象的各種其他方式。 `attrs.py` ```py #!/usr/bin/env python # attr.py def fun(): pass print(hasattr(object, '__doc__')) print(hasattr(fun, '__doc__')) print(hasattr(fun, '__call__')) print(getattr(object, '__doc__')) print(getattr(fun, '__doc__')) ``` `hasattr()`函數檢查對象是否具有屬性。 `getattr()`函數返回屬性的內容(如果有的話)。 ```py $ ./attr.py True True True The most base type None ``` `isinstance`函數檢查對象是否為特定類的實例。 ```py >>> print(isinstance.__doc__) Return whether an object is an instance of a class or of a subclass thereof. A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B) or ...`` etc. ``` 我們可以交互地描述一個函數。 `instance.py` ```py #!/usr/bin/env python # instance.py class MyObject(object): def __init__(self): pass o = MyObject() print(isinstance(o, MyObject)) print(isinstance(o, object)) print(isinstance(2, int)) print(isinstance('str', str)) ``` 眾所周知,一切都是 Python 中的對象; 偶數和字符串。 `object`是 Python 中所有對象的基本類型。 ```py $ ./instance.py True True True True ``` `issubclass()`函數檢查特定的類是否是另一個類的派生類。 `subclass.py` ```py #!/usr/bin/env python # subclass.py class Object(object): def __init__(self): pass class Wall(Object): def __init__(self): pass print(issubclass(Object, Object)) print(issubclass(Object, Wall)) print(issubclass(Wall, Object)) print(issubclass(Wall, Wall)) ``` 在我們的代碼示例中,`Wall`類是`Object`類的子類。 `Object`和`Wall`本身也是它們的子類。 `Object`類不是`Wall`類的子類。 ```py $ ./subclass.py True False True True ``` `__doc__`屬性提供了有關對象的一些文檔,`__name__`屬性包含對象的名稱。 `namedoc.py` ```py #!/usr/bin/env python # namedoc.py def noaction(): '''A function, which does nothing''' pass funcs = [noaction, len, str] for i in funcs: print(i.__name__) print(i.__doc__) print("-" * 75) ``` 在我們的示例中,我們創建了三個函數的列表:一個自定義函數和兩個本機函數。 我們瀏覽列表并打印`__name__`和`__doc__`屬性。 ```py $ ./namedoc.py noaction A function, which does nothing --------------------------------------------------------------------------- len Return the number of items in a container. --------------------------------------------------------------------------- str str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'. --------------------------------------------------------------------------- ``` 這是輸出。 最后,還有一個`callable()`函數。 該函數檢查對象是否為可調用對象(函數)。 `callable.py` ```py #!/usr/bin/env python # callable.py class Car(object): def setName(self, name): self.name = name def fun(): pass c = Car() print(callable(fun)) print(callable(c.setName)) print(callable([])) print(callable(1)) ``` 在代碼示例中,我們檢查三個對象是否可調用。 ```py print(callable(fun)) print(callable(c.setName)) ``` `fun()`函數和`setName()`方法是可調用的。 (方法是綁定到對象的函數。) ```py $ ./callable.py True True False False ``` 在 Python 教程的這一部分中,我們討論了 Python 中的自省。 在`inspect`模塊中可以找到更多進行內省的工具。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看