Python编程:获取一个类对象的属性和方法
  TEZNKK3IfmPf 2023年11月15日 35 0

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模块

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月15日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年05月31日   32   0   0 python开发语言
  TEZNKK3IfmPf   2024年05月31日   25   0   0 python
  TEZNKK3IfmPf   2024年05月31日   25   0   0 python
TEZNKK3IfmPf