Python编程:获取一个类对象的属性和方法

简介: Python编程:获取一个类对象的属性和方法

python3.6 下测试

# -*- coding: utf-8 -*-
class Demo(object):
    name = "demo"
    def instance_func(self):
        pass
    @classmethod
    def class_func(cls):
        pass
    @staticmethod
    def static_func():
        pass
def print_attrs_by_dict():
    """打印出属性"""
    print(Demo.__dict__.keys())
    # dict_keys(['__module__', 'name', 'instance_func',
    # 'class_func', 'static_func', '__dict__', '__weakref__',
    # '__doc__'])
def print_attrs_by_dir():
    """ 过滤所有属性 """
    print(dir(Demo))
    # ['__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__', 'class_func', 'instance_func', 'name', 'static_func']
def filter_attrs_by_inspect():
    """ 过滤出函数 少了类方法:class_func """
    import inspect
    print([i for i in dir(Demo) if inspect.isfunction(getattr(Demo, i))])
    # ['instance_func', 'static_func']
def filter_attrs_by_callable():
    """过滤出可调用的函数 """
    print([i for i in dir(Demo) if callable(getattr(Demo, i))])
    # ['__class__', '__delattr__', '__dir__', '__eq__', '__format__',
    # '__ge__', '__getattribute__', '__gt__', '__hash__','__init__',
    # '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__',
    # '__reduce__', '__reduce_ex__','__repr__', '__setattr__',
    # '__sizeof__', '__str__', '__subclasshook__', 'class_func',
    # 'instance_func', 'static_func']
if __name__ == '__main__':
    print_attrs_by_dict()
    print_attrs_by_dir()
    filter_attrs_by_inspect()
    filter_attrs_by_callable()

参考:

Python中如何获取类属性的列表

python–inspect模块

相关文章
|
安全 测试技术 数据库
Python编程--sys模块及OS模块简单用例
Python编程--sys模块及OS模块简单用例
180 1
|
JSON 数据格式 Python
Python编程:利用JSON模块编程验证用户
Python编程:利用JSON模块编程验证用户
113 1
|
数据处理 Python
Python编程-利用datetime模块生成当前年份之前指定的间隔所有年份的日期列表和csv文件
Python编程-利用datetime模块生成当前年份之前指定的间隔所有年份的日期列表和csv文件
206 1
|
人工智能 安全 Java
Python 多线程编程实战:threading 模块的最佳实践
Python 多线程编程实战:threading 模块的最佳实践
449 5
|
安全 调度 Python
什么是Python中的事件驱动编程?如何使用`asyncio`模块实现异步事件处理?
【2月更文挑战第4天】【2月更文挑战第9篇】什么是Python中的事件驱动编程?如何使用`asyncio`模块实现异步事件处理?
361 0
|
缓存 分布式计算 自然语言处理
Python语言的函数编程模块
Python语言的函数编程模块
|
并行计算 程序员 API
Python多进程编程:利用multiprocessing模块实现并行计算
Python多进程编程:利用multiprocessing模块实现并行计算
1212 0
|
前端开发 安全 Unix
Python编程手册系列 - 日历、日期、时间相关内建模块详解
Python编程手册系列 - 日历、日期、时间相关内建模块详解
215 0
|
开发者 Python
< Python全景系列-7 > 提升Python编程效率:模块与包全面解读
< Python全景系列-7 > 提升Python编程效率:模块与包全面解读
193 0
|
SQL 关系型数据库 MySQL
Python编程:MySQLdb模块对数据库的基本增删改查操作
Python编程:MySQLdb模块对数据库的基本增删改查操作
190 1