欢迎访问宙启技术站
智能推送

在Python中使用dir()函数探索模块和对象的属性和方法

发布时间:2023-06-05 20:15:18

dir()函数是Python自带的函数,可以用于查看模块或对象里面包含的所有属性和方法。它的使用方法很简单,只需要在括号内写入要查看的模块和对象即可返回这个模块或对象所包含的所有属性和方法的列表。

1、探索模块的属性和方法

在Python中,模块就是一个.py后缀的文件,可以用于批量编程时调用。我们可以用dir()函数探索模块中的属性和方法。

如下所示,我们创建一个test.py模块,其中包含两个函数和一个变量:

# test.py
num = 123

def hello():
    print('hello')

def world(): 
    print('world')

在Python解释器中输入以下代码:

import test
print(dir(test))

output:

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'hello', 'num', 'world']

上述代码所输出的结果为test模块下的所有属性和方法。

首先,我们注意到了以双下划线开始和结束的属性(如__file__、 __name__和 __spec__),这些是Python内置的属性,在模块中都可以找到。其他的属性和方法就是我们在test.py里面定义的。这个过程非常有用,能够帮助我们更好地了解模块的内容。

2、探索对象的属性和方法

在Python中,一切皆是对象。对于对象,我们同样可以使用dir()函数来查看对象的属性和方法。我们可以使用如下代码来获取一个int对象的所有属性和方法:

num = 123
print(dir(num))

output:

['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

输出结果最前面是以双下划线开始和结束的特殊方法,而其他属性和方法则根据字母表顺序列出。

需要注意的是,部分属性和方法是对象特有的,这就说明对于不同类型的对象,所拥有的属性和方法可能是不同的。

dir()函数不仅仅适用于内置类型的对象,也适用于用户自定义类型的对象。例如,创建一个Person类并实例化为一个对象:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def say_hello(self):
        print('Hello, my name is', self.name)

p = Person('Jack', 22)
print(dir(p))

output:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name', 'say_hello']

除了像__class__和__dir__这样的离奇方法,我们可以看到name、age和say_hello方法。这些都是Person对象拥有的属性和方法。

总之,使用dir()函数可以更深入地探索任意对象的属性和方法,这个方法对于Python编程和调试非常有用。