P进阶_(dir函数)

本文详细介绍了Python内置的dir()函数,包括其作用、参数和返回结果。dir()函数可以用来获取对象的属性列表,对于模块、类和其他对象有不同的表现。在不传参数时,它返回当前作用域的变量名;传入对象时,返回对象及其类的属性。此外,还展示了如何过滤掉以_开头的私有方法。dir()函数在查看对象支持的功能或查找可调用方法时非常有用。
摘要由CSDN通过智能技术生成

定义:

"""


dir([object]) -> list of strings

If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; otherwise
the default dir() logic is used and returns:
  for a module object: the module's attributes.
  for a class object:  its attributes, and recursively the attributes
    of its bases.
  for any other object: its attributes, its class's attributes, and
    recursively the attributes of its class's base classes.


"""

翻译:

"""

dir([object]) -> 字符串列表 如果在没有参数的情况下调用,则返回当前范围内的名称。
否则,返回一个按字母顺序排列的名称列表,其中包括(部分)给定对象的属性,以及可从该对象访问的属性。
如果对象提供了一个名为 __dir__ 的方法,它将被使用;
否则使用默认的 dir() 逻辑并返回: 对于模块对象:模块的属性。
对于一个类对象:它的属性,以及递归它的基类的属性。对于任何其他对象:其属性、其类的属性以及递归其类的基类的属性。

"""

不带参数

dir_res = dir()
print(dir_res)
#  ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']

带参数

# 这里自定义个文件导入
import dir_demo

dir_res = dir(dir_demo)
print(dir_res)


# ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'dir_dem']

dir_demo.py

def dir_dem(*args, **kwargs):
    pass

去除私有方法

(双下划线__开头和结尾)

dir_res = [i for i in dir(dir_demo) if not i.startswith('_')]
print(dir_res)

非自定义代码

# python 自带函数

dir_res = [i for i in dir(list) if not i.startswith('_')]
print(dir_res)
# ['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

# 主要用途

# 返回参数对象的有效属性列表 查看文件下面都支持哪些函数
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值