• 【python】python内置函数——dir()获取对象的属性和方法


    dir()函数

    • 不带参数时,返回当前范围内的变量、方法和定义的类型列表;
    • 带参数时,返回参数的属性、方法列表;
    • 如果参数包含方法__dir__(),该方法将会被调用;
    • 如果参数不包含__dir__(),该方法将最大限度地手机参数信息

    dir()函数的语法格式:

    dir([object])

    参数 object是对象、变量、类型。

    返回值是模块的属性列表。

    如下所示:

    1. # -*- coding: utf-8 -*-
    2. """
    3. @File : func_dir.py
    4. @Author : 小地瓜重新去华容道工作
    5. @E-Mail : zoya.zh@qq.com
    6. @Time : 22/8/28
    7. """
    8. print(dir()) # 获取当前模块的属性列表
    9. print(dir(list())) # 获取列表的方法
    10. class MyTestDir:
    11. def __init__(self):
    12. self.name="dir"
    13. def myPrint(self):
    14. print("dir() test...")
    15. print(dir(MyTestDir())) # 获取类MyTestDir的属性和方法

    显示结果:

    1. ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
    2. ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__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']
    3. ['__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__', 'myPrint', 'name']

    注意:

    __xxx__格式的方法是python提供的内置方法或属性。

    全文参考:Python dir() 函数 | 菜鸟教程 (runoob.com)

  • 相关阅读:
    Minio + Nginx 实现静态资源对外访问
    pnpm快速创建 Vue.js 项目(npm类似)
    HTML开篇之安装VSvode(用记事本编辑HTML)
    MySQL的主从复制与读写分离详解
    人工智能在网络流量分析中的研究与应用
    C Primer Plus(6) 中文版 第1章 初识C语言 1.7 使用C语言的7个步骤
    NLP-新闻主题分类任务
    day 4
    力扣第46题 全排列 c++ 回溯 秒杀题 思路+注释
    Java+JSP+MySQL基于SSM的医院挂号就诊系统-计算机毕业设计
  • 原文地址:https://blog.csdn.net/sinat_41752325/article/details/126575485