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