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']


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...