Python dir()函数
在Python中,dir()
函数是一个内置函数,用于列出指定对象的属性和方法。如果没有指定对象,则默认使用当前作用域中的所有对象。dir()
函数返回一个字符串列表,包含指定对象的所有属性和方法名称。
dir()函数示例
以下是一些dir()
函数的示例:
- 列出当前作用域中的所有对象的名称:
print(dir())
运行效果:
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
import math
print(dir(math))
运行效果:
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
s = "hello, world"
print(dir(s))
运行效果:
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
__dir__()
方法的类:
class Test:
def __dir__(self):
return ['a','b','c']
t = Test()
print(dir(t))
运行效果:
['a', 'b', 'c']
需要注意的是,dir()
函数返回的列表中还包括一些双下划线开头和结尾的名称,这些名称通常是Python中的特殊方法或属性。例如,__len__()
方法用于获取对象的长度,__str__()
方法用于将对象转换为字符串等。这些特殊方法和属性在Python中具有特殊的含义,可以用来实现自定义的行为和功能。