brain storm
brain storm

Reputation: 31252

how to get a dict of instance fields with in a class definition in python?

For functions, the locals() method return the local variables inside the function eg:

>>> def f():
...  x=5
...  y=6
...  return locals()
... 
>>> f()
{'y': 6, 'x': 5}
>>> 

I am looking for something similar in a class.

>>> class c(object):
...     x=5
...     y=6
...     def local(self):
...       dict={}
...       dict['x']=self.x
...       dict['y']=self.y
...       return dict
... 
>>> v=c()
>>> v.local()
{'y': 6, 'x': 5}

but I want to do this in multiple classes and I have lot of fields defined with in a class. so I am wondering if there is a built-in method that returns a dict of all the instance attributes

Actually I am using this in Django, where i want to pass the instance fields to a re-direct url that accepts them as key-word arguements

EDIT: I want to get a dict of instance attributes with in the class itself. I do not want to make an instance to the get dict out.

I tried this out:

>>> class c(object):
...    x=5
...    y=10
...    def local(self):
...      return c.__dict__
... 
>>> v=c()
>>> v.local()
<dictproxy object at 0x10f640ef8>
>>> 

It is not returning a dictionary of key-value of fields and its values

Upvotes: 0

Views: 411

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122036

Yes, you can access the instance's dictionary of objects as:

v.__dict__

or the class's at

c.__dict__

Or, as Chiel92 points out, using vars(c)/vars(v).

You can make this a class method:

class c:

    x=2
    y=5

    @classmethod
    def attrs(cls):
        return vars(cls)

But c.attrs() seems no better than c.__dict__ or vars(c).

Note that you shouldn't call your own dictionaries dict, as this shadows the Python built-in.

Upvotes: 3

Related Questions