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中具有特殊的含义,可以用来实现自定义的行为和功能。

原创内容,如需转载,请注明出处;

本文地址: https://www.perfcode.com/python-built-in-functions/python-dir.html

分类: 计算机技术
推荐阅读:
Python webbrowser模块的详细用法 webbrowser是python下一个内置的模块,该模块提供了一个高级接口,使你可以调用计算机中的浏览器以打开基于WEB的文档,比如常见的html网页;
Python计算卡特兰数(catanlan number) 卡特兰数(Catalan number),是组合数学中一种常出现于各种计数问题中的数列;本文使用Python来计算卡特兰数;
最新阿里云免费SSL证书申请教程 2021年最新申请阿里云免费SSL证书流程如下:
如何查看CPU的出厂日期 通常情况下,CPU的出厂日期是写在CPU的标签或者包装盒上的。如果您已经安装了CPU,则可以通过操作系统或者第三方软件来查看CPU的出厂日期。以下是一些方法:
SQL重命名数据库 当您需要更改数据库名称时,将使用RENAME DATABASE;
SQL注入万能语句' or 1='1详解 ' or 1='1是SQL注入的万能语句,可以通过它轻松改变SQL语句的逻辑关系,从而产生背离原SQL语句的效果,比如绕过用户密码验证;