程式扎記: [ Python 常見問題 ] How list all fields of an class in Python (and no methods)?

標籤

2016年10月3日 星期一

[ Python 常見問題 ] How list all fields of an class in Python (and no methods)?

Source From Here
Question
Suppose o is a Python object, and I want all of the fields of o, without any methods or __stuff__. How can this be done?

How-To
You can get it via the __dict__ attribute, or the built-in vars function, which is just a shortcut. For example:
  1. class A:  
  2.     V1="V1"  
  3.     def __init__(self):  
  4.         self.v1="v1"  
  5.     def hello(self):  
  6.         print "Hello"  
Then you can try below samples:
>>> a = A()
>>> dir(a)
['V1', '__doc__', '__init__', '__module__', 'hello', 'v1']
>>> a.__dict__
{'v1': 'v1'}
>>> vars(a)
{'v1': 'v1'}
>>> h = getattr(a, 'hello')
>>> h
>
>>> h()
Hello
>>> callable(h)
True
>>> [method for method in dir(a) if callable(getattr(a, method))]
['__init__', 'hello']
>>> [method for method in dir(a) if not callable(getattr(a, method))]
['V1', '__doc__', '__module__', 'v1']


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!