Python dir() 函数2024年9月26日 | 阅读 2 分钟 Python dir() 函数返回当前本地作用域中的名称列表。 如果调用该方法的对象具有名为 __dir__() 的方法,则将调用此方法,并且必须返回属性列表。 它接受一个对象类型参数。 函数的签名如下所示。 签名参数object:它接受一个可选参数。 返回它返回对象的有效属性列表。 让我们看一些 dir() 函数的例子来理解它的功能。 Python dir() 函数示例 1让我们创建一个简单的例子来获取有效属性的列表。 它接受一个可选的参数。 输出 ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__'] Python dir() 函数示例 2如果我们将参数传递给此函数,它将返回与该对象相关的属性。 见下例。 输出 ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index'] Python dir() 函数示例 3输出 ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] Python dir() 函数示例 4如果 dir() 函数已经在对象中定义,则将调用该函数。 输出 [10, 20, 30] 下一个主题Python 函数 |
我们请求您订阅我们的新闻通讯以获取最新更新。