python在编程中总是不清楚对象的成员方法,通过一些内置函数可以在运行环境中得到成员函数和成员变量。当然也可以应用inspect库函数查看。
class A(object):
def __init__(self, x):
self.x = x
obj = A()
print(obj.__dict__)
print(vars(obj))
print(dir(obj))
运行结果:
{'x': 2}
{'x': 2}
['__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__', 'get_x', 'x']
从运行结果来看,成员变量__dict__
和vars()都可以抽取对象的成员变量做成字典。但在实际使用中发现有时候可能会出错,返回只有类的变量类型,而没有成员变量。类似于
{'_sa_instance_state': <sqlalchemy.orm.state.InstanceState object at 0x0000024F3B6FFE48>}
调试发现,如果出现这种错误,可以调用
print(dict(obj))
来展示成员变量。但是对于不可迭代的类,dict函数不可用。
dir函数可以抽取对象可用的所有成员函数。