首页Python【Python内置函数】d...

【Python内置函数】dir()函数

Python 提供了许多内置函数,这些函数是Python语言的一部分,可以直接在Python程序中使用而无需导入任何模块。

本系列将会陆续整理分享一些的Python内置函数。

文章配套代码获取有以下两种途径:
  • 通过百度网盘获取:
链接:https://pan.baidu.com/s/11x9_wCZ3yiYOe5nVcRk2CQ?pwd=mnsj 提取码:mnsj
  • 前往GitHub获取
https://github.com/returu/Python_built-in_functions





01
简介

dir() 函数是 Python 中的一个内置函数,用于获取对象所有属性和方法的列表(字符串形式)。
当你对一个对象不太了解时,可以使用 dir() 查看它的属性和方法。这对于了解对象的结构非常有用,特别是在使用大型库或模块时。另外,在某些动态编程场景中,可以使用 dir() 获取的属性名称来动态调用对象的方法或访问属性。

dir() 函数的基本语法如下:

dir(object)
参数说明:
  • object:可选参数,想要列出属性和方法的对象包括模块、类、实例等。如果不提供参数,该函数将列出当前局部和全局符号表中的名称。。

返回值:

  •  如果传递参数,则返回该对象的属性和方法的列表。 返回的列表中通常会包含一些以双下划线开头和结尾的特殊方法如 __init____str__ 等),这些方法通常用于内部实现。

  • 如果不传递参数,则返回当前作用域中的所有变量、方法的列表。

02
使用:

下面是一些使用 dir() 函数的示例:

  • 不传递参数:

如果不传递参数,将返回当前作用域中的所有变量、方法的字符串列表。


print(dir())
# 输出:['In', 'Out', '_', '_1', '_2', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__pandas', '__session__', '__spec__', '_dh', '_i', '_i1', '_i2', '_i3', '_ih', '_ii', '_iii', '_oh', 'dataframe_columns', 'dataframe_hash', 'dtypes_str', 'exit', 'get_dataframes', 'get_ipython', 'getpass', 'hashlib', 'import_pandas_safely', 'is_data_frame', 'json', 'open', 'quit']



def my_function():
    a = 10
    b = "hello"
    print("当前作用域的变量和方法:", dir())
 
my_function()
# 输出:当前作用域的变量和方法: ['a', 'b']


  • 传递参数:

如果传递参数,将返回该对象的属性和方法的字符串列表。

  • 示例 1:获取内置对象的属性和方法列表

此时将返回内置对象的所有方法和属性,例如 __add____class__等。dir() 函数可以用于探索模块和类的内置方法,更好地理解 Python 的内置类型和功能。


print(dir([]))  # 列表对象的属性和方法
print(dir(""))  # 字符串对象的属性和方法
# 输出:['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
# 输出:['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__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']


  • 示例 2:获取模块的属性和方法列表

此时将返回模块中定义的所有属性和方法名称的列表。


import math

print(dir(math))
# 输出:['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', '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', 'sumprod', 'tan', 'tanh', 'tau', 'trunc', 'ulp']


  • 示例 3:获取类的属性和方法列表

此时将返回类实例的所有属性和方法名称的列表,包括继承自基类的方法。

例如下面的示例中,BaseClass是一个基类,有一个base_attribute属性。因MyClass继承BaseClassMyClass的实例obj将同时拥有 base_attribute 和 x 属性。


# 基类,它有一个属性 base_attribute
class BaseClass:
    def __init__(self):
        self.base_attribute = "Base Attribute"

class MyClass(BaseClass):
    def __init__(self):
        super().__init__()  # 调用基类的构造函数
        self.x = 10
    
    def my_method(self):
        pass

obj = MyClass()
print(dir(obj))
# 输出:['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'base_attribute', 'my_method', 'x']


  • 示例 4:动态属性访问

结合 getattr() 函数,可以根据字符串名称动态访问对象的属性或方法。


class MyClass:
    def __init__(self):
        self.name = "MyClass"

    def greet(self):
        print("Hello from MyClass!")

obj = MyClass()

# 根据条件动态查找对象的属性
if hasattr(obj, "name"):
    print("对象的名称属性为:", getattr(obj, "name"))
# 输出:对象的名称属性为: MyClass

method_name = "greet"
if method_name in dir(obj):
    getattr(obj, method_name)()
# 输出:Hello from MyClass!


本篇文章来源于微信公众号: 码农设计师

RELATED ARTICLES

欢迎留下您的宝贵建议

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments