在python中显示对象的属性

Ana*_*ake 9 python oop list

我想显示一个给对象的属性,并想知道是否有一个python函数.例如,如果我有以下类中的对象:

class Antibody():

    def __init__(self,toSend):

        self.raw = toSend
        self.pdbcode = ''
        self.year = ''
Run Code Online (Sandbox Code Playgroud)

我可以获得类似于此类似的输出:

['self.raw','self.pdbcode','self.year']
Run Code Online (Sandbox Code Playgroud)

谢谢

Sve*_*ach 15

试试dir(self).它将包括所有属性,而不仅仅是"数据".


NPE*_*NPE 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()
Run Code Online (Sandbox Code Playgroud)