【问题标题】:How to find all Python built-in private variables such as __file__, __name__如何查找所有 Python 内置的私有变量,例如 __file__、__name__
【发布时间】:2014-07-12 03:34:55
【问题描述】:

我想知道__file____name__等所有Python内置私有变量,以及它们的用途。

但我在 www.python.org 中没有看到所有 Python 内置私有变量的文档。

我知道dirvars

那么,如何找到它们?

【问题讨论】:

    标签: python document private private-members built-in


    【解决方案1】:

    你说什么:

    >>> dir()
    ['__builtins__', '__doc__', '__name__', '__package__', 'f']
    >>> [ i for i in dir() if i.startswith("__") and i.endswith("__")]
    ['__builtins__', '__doc__', '__name__', '__package__']
    

    你可以定义一个辅助函数:

    >>> def getprivates(obj):
            return [i for i in dir(obj) if i.startswith("__") and i.endswith("__")]
    

    并应用于任何对象引用,甚至是 dir() 本身:

    >>> getprivates(dir())
    ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__']
    

    【讨论】:

    • 他确实说他知道目录。
    【解决方案2】:

    隐藏的属性有时被称为魔术方法(用于对象),作为参考,我会查看 Python docs on the data model,它相当全面,可能涵盖了您要查找的所有属性。

    在你了解了 hidden 属性之后,你可能知道你想要得到什么,但是隐藏的属性可能会因实现而异,因此要将其抽象出来,请使用检查模块:

    import inspect
    

    要获得很多的信息:

    inspect.getmembers(inspect) 
    

    要获取文件和有关模块的更多信息:

    >>> inspect.getfile(inspect)
    '/usr/lib/python2.7/inspect.pyc'
    >>> inspect.getmoduleinfo(inspect.getfile(inspect))
    ModuleInfo(name='inspect', suffix='.pyc', mode='rb', module_type=2)
    

    【讨论】:

      猜你喜欢
      • 2017-04-10
      • 1970-01-01
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 2014-08-19
      • 1970-01-01
      • 2011-01-23
      相关资源
      最近更新 更多