是否有一种方法可以获取所有属性/方法/字段等。Python中对象的?

vars()接近我想要的,但它不能工作,除非对象有__dict__,这并不总是真的(例如,它不是一个列表,dict等)。


当前回答

我使用__dict__和dir(<实例>)

例子:

class MyObj(object):
  def __init__(self):
    self.name = 'Chuck Norris'
    self.phone = '+6661'

obj = MyObj()
print(obj.__dict__)
print(dir(obj))

# Output:  
# obj.__dict__ --> {'phone': '+6661', 'name': 'Chuck Norris'}
#
# dir(obj)     --> ['__class__', '__delattr__', '__dict__', '__doc__',
#               '__format__', '__getattribute__', '__hash__', 
#               '__init__', '__module__', '__new__', '__reduce__', 
#               '__reduce_ex__', '__repr__', '__setattr__', 
#               '__sizeof__', '__str__', '__subclasshook__', 
#               '__weakref__', 'name', 'phone']

其他回答

你可以使用dir(your_object)来获取属性,使用getattr(your_object, your_object_attr)来获取值

用法:

for att in dir(your_object):
    print (att, getattr(your_object,att))

我使用__dict__和dir(<实例>)

例子:

class MyObj(object):
  def __init__(self):
    self.name = 'Chuck Norris'
    self.phone = '+6661'

obj = MyObj()
print(obj.__dict__)
print(dir(obj))

# Output:  
# obj.__dict__ --> {'phone': '+6661', 'name': 'Chuck Norris'}
#
# dir(obj)     --> ['__class__', '__delattr__', '__dict__', '__doc__',
#               '__format__', '__getattribute__', '__hash__', 
#               '__init__', '__module__', '__new__', '__reduce__', 
#               '__reduce_ex__', '__repr__', '__setattr__', 
#               '__sizeof__', '__str__', '__subclasshook__', 
#               '__weakref__', 'name', 'phone']

您可能需要的是dir()。

The catch is that classes are able to override the special __dir__ method, which causes dir() to return whatever the class wants (though they are encouraged to return an accurate list, this is not enforced). Furthermore, some objects may implement dynamic attributes by overriding __getattr__, may be RPC proxy objects, or may be instances of C-extension classes. If your object is one these examples, they may not have a __dict__ or be able to provide a comprehensive list of attributes via __dir__: many of these objects may have so many dynamic attrs it doesn't won't actually know what it has until you try to access it.

在短期内,如果dir()不够,你可以编写一个函数,遍历__dict__对象,然后遍历obj.__class__.__mro__中的所有类;尽管这只适用于普通的python对象。从长远来看,你可能不得不使用鸭子类型+假设-如果它看起来像一只鸭子,交叉手指,并希望它有。羽毛。

使用内置函数dir()。