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...
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()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。
原文链接:pengshiyu.blog.csdn.net/article/details/89436604
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)