Python中dir(string)和dir(someString)之间的区别?

2024-10-06 12:20:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始用python学习编程。当我得知是否要列出我编写的所有字符串模块时:

import string
print dir(string)

结果:

['Formatter', 'Template', '_TemplateMetaclass', 'builtins', 'doc', 'file', 'name', 'package', '_float', '_idmap', '_idmapL', '_int', '_long', '_multimap', '_re', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'atof', 'atof_error', 'atoi', 'atoi_error', 'atol', 'atol_error', 'capitalize', 'capwords', 'center', 'count', 'digits', 'expandtabs', 'find', 'hexdigits', 'index', 'index_error', 'join', 'joinfields', 'letters', 'ljust', 'lower', 'lowercase', 'lstrip', 'maketrans', 'octdigits', 'printable', 'punctuation', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitfields', 'strip', 'swapcase', 'translate', 'upper', 'uppercase', 'whitespace', 'zfill']

但这是怎么回事:

^{pr2}$

结果:

['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']

为什么结果不同?在


Tags: namestringindexdocasciierrorsplitcenter
1条回答
网友
1楼 · 发布于 2024-10-06 12:20:50

在Python控制台:

>>> import string
>>> type(string)
<type 'module'>

>>> type("someValues")
<type 'str'>

>>> help(dir)

dir([object]) -> list of strings

If called without an argument, return the names in the current scope. Else, return an alphabetized list of names comprising (some of) the >attributes of the given object, and of attributes reachable from it. If the object supplies a method named dir, it will be used; otherwise the default dir() logic is used and returns:

for a module object: the module's attributes.
for a class object:  its attributes, and recursively the attributes
  of its bases.
for any other object: its attributes, its class's attributes, and
  recursively the attributes of its class's base classes.

因此,dir(string)返回^{}模块的属性,而 dir("someValues")返回^{}类的属性及其实例的属性。为了正确区分,请看Modules, Classes, and Objects。在

相关问题 更多 >