2018年5月21日 星期一

[ Python 常見問題 ] Get all object attributes in Python?

Source From Here 
Question 
Is there a way to get all attributes/methods/fields/etc. of an object in Python

vars() is close to what I want, but it doesn't work unless an object has a __dict__, which isn't always true (e.g. it's not true for a list, a dict, etc.). 

How-To 
You can leverage built-in API dir to know all attributes/methods/fields of an object. e.g.: 
  1. >>> class Person:  
  2. ...     def __init__(self, name, age):  
  3. ...             self.name = name  
  4. ...             self.age = age  
  5. ...     def a(self):  
  6. ...             return self.age  
  7. ...     def n(self):  
  8. ...             return self.name  
  9. ...  
  10. >>> john = Person('John'37)  
  11. >>> john.a()  
  12. 37  
  13. >>> john.n()  
  14. 'John'  
  15. >>> dir(john)  
  16. ['__doc__''__init__''__module__''a''age''n''name']  


Then you can access the attribute(s) of an object by getattr
  1. >>> for attr in john.__dict__.keys():  
  2. ...     if attr.startswith('__'):  
  3. ...             continue  
  4. ...     attr_obj = getattr(john, attr)  
  5. ...     if callable(attr_obj):  
  6. ...             print('attr \'{}\' is a function or method'.format(attr))  
  7. ...     else:  
  8. ...             print('attr of {} with value={}'.format(attr, attr_obj))  
  9. ...  
  10. attr of age with value=37  
  11. attr of name with value=John  
  12. >>> getattr(john, 'a')  
  13. 0x7f0c64438d88>>  
  • >>> callable(getattr(john, 'a'))  
  • True  
  • From above example, you can notice that the __dict__ won't contain method(s)! 

    Supplement 
    How to get an attribute from an object in Python

    沒有留言:

    張貼留言

    [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...