我想显示一个给对象的属性,并想知道是否有一个python函数。 例如,如果我有以下类中的对象:
class Antibody():
def __init__(self,toSend):
self.raw = toSend
self.pdbcode = ''
self.year = ''
我可以得到类似于此类似的输出:
['self.raw','self.pdbcode','self.year']
感谢
答案 0 :(得分:15)
试试dir(self)
。它将包括所有属性,而不仅仅是“数据”。
答案 1 :(得分:8)
以下方法为您的班级实例打印['self.pdbcode', 'self.raw', 'self.year']
:
class Antibody():
...
def get_fields(self):
ret = []
for nm in dir(self):
if not nm.startswith('__') and not callable(getattr(self, nm)):
ret.append('self.' + nm)
return ret
a = Antibody(0)
print a.get_fields()
答案 2 :(得分:2)
喜欢这个
class Antibody:
def __init__(self,toSend):
self.raw = toSend
self.pdbcode = ''
self.year = ''
def attributes( self ):
return [ 'self.'+name for name in self.__dict__ ]
答案 3 :(得分:0)
a = Antibody(0)
map(lambda attr: 'self.%s'%(attr), filter(lambda attr: not callable(getattr(a, attr)), a.__dict__))