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

分类: 计算机技术
推荐阅读:
如何查看CPU序列号 请注意,某些CPU可能没有序列号,或由于制造商实施的安全功能而无法获取序列号。此外,序列号可能不是针对您特定的CPU型号而独有的,可能在多个CPU之间共享。
Requests详细教程 Requests 是一个功能强大、优雅而简单的 Python HTTP库;使用Requests发送网络请求整个过程将变得非常简单。
Rust中的数据类型 在本文中,将介绍Rust中的整型、浮点型、布尔类型、字符类型、元组类型、数组类型的声明和简单使用方法;
在Linux终端右上角实时显示时间 在Linux系统下,可以通过一条命令在终端的右上角显示当前系统的时间:
Python读写JSON文件、解析JSON JSON(JavaScript Object Notation)是一种轻量级的数据交换格式;本文将通过多个例子讲解在Python中如何读写json文件,如何解析JSON内容,以及如何将JSON对象与Python字典相互转换;
SSH证书登录提示WARNING: UNPROTECTED PRIVATE KEY FILE解决方法 使用SSH登录服务器时,出现 WARNING: UNPROTECTED PRIVATE KEY FILE! 提示,其原因是密钥文件权限太开放,SSH要求密钥文件不能被其他用户房访问;