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.
CodePudding user response:
You're looking for vars
example:
return vars(self)
Output:
{'value': 0, 'src': 'admin'}
CodePudding user response:
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.
CodePudding user response:
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())