【问题标题】:Regarding dir()关于 dir()
【发布时间】:2014-01-12 23:04:20
【问题描述】:

最初我试图找到dir(re),但发现我有引号。

为清楚起见进行编辑:

"re" 不是字符串吗?所以dir("re") == dir(string)?输出不一样。这基本上就是我想知道的。

为 cmets 编辑:

我可能会误解,但dir 不是返回模块内所有函数的列表吗?此外,当我在"re" 上调用dir 时,它会给我一个函数列表。不返回错误。

edit2:是的dir。一直在 ruby​​ 和 python 项目之间切换,出于某种原因,我脑子里有 def。对不起xD

【问题讨论】:

  • 我不明白你的问题。 def("re") 不是有效的 Python 代码。您还在谈论模块和功能之间切换,然后您最后会遇到一个完全不同的问题,这也不清楚。请澄清您的要求。
  • 也许您的意思是 dir,它返回给定范围内的名称列表?您仍然需要手动过滤掉函数。例如通过遍历所有名称并检查 type(x) == types.FunctionType
  • 您是否设法将def 的意思写到dir 几乎十次?
  • 读取the docs,dir(obj) 返回对象obj 的“有效属性列表”。而python中的一切都是一个对象,无论是模块re,还是字符串're'
  • 关于您更新的问题:dir("re") isdir(str) 相同。注意 Python 中字符串的类型是<type 'str'> -- 试试print type("re")

标签: python function module dir


【解决方案1】:

我认为您需要澄清dir 的作用。

dir 是一个 Python 内置函数,根据是否提供参数,它可以执行以下两种操作之一:

  1. 如果没有参数,它会返回当前范围内的名称列表。这些名称表示为字符串。

  2. 使用参数,它返回属于该参数的属性和方法的列表。再次,它将是一个字符串列表。

下面是第一个动作的演示:

>>> num = 1 # Just to demonstrate
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'num']
>>>

这是第二个的演示:

>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>>

此外,如果它的参数是一个 Python 模块,那么dir 将列出该模块中包含的名称:

>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_mercurial', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit',
'getrefcount', 'getsizeof', 'gettrace', 'getwindowsversion', 'hexversion', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info',
'warnoptions', 'winver']
>>>

现在,您在问题中说dir("re") 的输出不等于dir(string)。对此,我想说几句:

  1. 如果string 是字符串文字,如@9​​87654332@,那么它应该工作:

    >>> dir("re") == dir("string")
    True
    >>> 
    
  2. 如果 "re" 实际上是 re 模块,那么您看到的行为是预期的,因为该模块不是字符串。

  3. 如果您希望 dir("re") 列出 re 模块中包含的名称,那您就错了。您不能使用字符串引用模块。相反,您必须先显式导入它:

    >>> dir("re")  # The output is the same as doing dir(str)
    ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
    >>>
    >>> import re
    >>> dir(re) # The output is for the re module, not str
    ['DEBUG', 'DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'S', 'Scanner', 'T', 'TEMPLATE', 'U', 'UNICODE', 'VERBOSE', 'X', '_MAXCACHE', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__version__', '_alphanum', '_cache', '_cache_repl', '_compile', '_compile_repl', '_expand', '_pattern_type', '_pickle', '_subx', 'compile', 'copy_reg', 'error', 'escape', 'findall',  'finditer', 'match', 'purge', 'search', 'split', 'sre_compile', 'sre_parse', 'sub', 'subn', 'sys', 'template']
    >>>
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    • 2015-01-05
    • 2020-12-04
    • 2011-07-29
    • 2019-10-23
    相关资源
    最近更新 更多