开发者

display an object's attributes in python

开发者 https://www.devze.com 2023-02-17 22:59 出处:网络
I would like to display the attributes of a give object and was wondering if there was a python function for it.

I would like to display the attributes of a give object and was wondering if there was a python function for it. For example if I had an object from the following class:

class Antibody():

    def __init__(self,toSend):

        self.raw = toSend
        self.pdbcode = ''
        self.year = ''

Could I get an output that looks something like this or something similar:开发者_运维知识库

['self.raw','self.pdbcode','self.year']

thanks


Try dir(self). It will include all attributes, not only "data".


The following method prints ['self.pdbcode', 'self.raw', 'self.year'] for an instance of your class:

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()


Like this

class Antibody:
    def __init__(self,toSend):
        self.raw = toSend
        self.pdbcode = ''
        self.year = ''
    def attributes( self ):
        return [ 'self.'+name for name in self.__dict__ ]


a = Antibody(0)

map(lambda attr: 'self.%s'%(attr), filter(lambda attr: not callable(getattr(a, attr)), a.__dict__))

0

精彩评论

暂无评论...
验证码 换一张
取 消