Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

display an object's attributes in python

Tags:

python

oop

list

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

like image 980
Anake Avatar asked Mar 17 '11 13:03

Anake


People also ask

How do I see all the attributes of an object in Python?

Use Python's vars() to Print an Object's Attributes The dir() function, as shown above, prints all of the attributes of a Python object.

What are object attributes in Python?

An instance/object attribute is a variable that belongs to one (and only one) object. Every instance of a class points to its own attributes variables. These attributes are defined within the __init__ constructor.


3 Answers

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

like image 149
Sven Marnach Avatar answered Sep 30 '22 07:09

Sven Marnach


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 image 45
NPE Avatar answered Sep 30 '22 09:09

NPE


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__ ]
like image 21
S.Lott Avatar answered Sep 30 '22 08:09

S.Lott