Max
Max

Reputation: 4408

Returning the inner namespace of a class as dictionary

Imagine we have a class like as below:

class P1(object):
    def __init__(self,value=0,src='admin'):
        self.value=value
        self.src=src

Is it possible to add a method that returns the name inner variables as a dictionary with name as the name and the value as the value like this:

def getDict(self):
    return dictionary(variables)

which returns:

{
  'value':0,
  'src':'admin'
}

PS I know it can be down by hard coding it, I am asking if there is Pythonic way of doing it with one method call.

Upvotes: 0

Views: 370

Answers (3)

user17083192
user17083192

Reputation:

Yes, you can use magic methods. If not create your own method which returns the dict of value and src. Your code:

class P1(object):
    def __init__(self,value=0,src='admin'):
        self.value=value
        self.src=src
    def getdict(self):
        return {"value":self.value,"src":self.src}      #manual return of dict


x=P1(5,"user")      #checking for non default values
print(x.getdict())

x=P1()              #checking for default values
print(x.getdict())

Upvotes: 1

Selcuk
Selcuk

Reputation: 59238

You can use __dict__:

A dictionary or other mapping object used to store an object’s (writable) attributes.

def getDict(self):
    return self.__dict__

or vars() builtin, which simply returns the __dict__ attribute:

return vars(self)

Warning: Note that this returns a reference to the actual namespace, and any changes you make to the dictionary will be reflected to the instance.

Upvotes: 1

Pedro Maia
Pedro Maia

Reputation: 2732

You're looking for vars example:

return vars(self)

Output:

{'value': 0, 'src': 'admin'}

Upvotes: 1

Related Questions