我想知道所有Python内置私有变量,例如__file__
,__name__
及其用途。
但我在www.python.org上看不到所有Python内置私有变量的文档。
我知道dir
和vars
。
那么,如何找到它们?
答案 0 :(得分:5)
你怎么说:
>>> 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("__")]
并申请任何对象引用:
>>> 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__']
答案 1 :(得分:2)
隐藏属性有时被称为魔术方法(对象),供参考,我会查看Python docs on the data model,这些内容相当全面,可能涵盖了您正在寻找的所有属性找到。
在您学会了隐藏属性之后,您可能知道自己想要获得什么,但隐藏属性可能因实现而异,因此要将其抽象出来,请使用inspect模块:< / p>
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)