Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading __dict__() on python class

Tags:

python

class

I have a class where I want to get the object back as a dictionary, so I implemented this in the __dict__(). Is this correct?

I figured once I did that, I could then use the dict (custom object), and get back the object as a dictionary, but that does not work.

Should you overload __dict__()? How can you make it so a custom object can be converted to a dictionary using dict()?

like image 450
code base 5000 Avatar asked Apr 23 '14 18:04

code base 5000


People also ask

What is the __ str __ method in Python?

Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object. This method must return the String object.

What is __ add __ in Python?

__add__ magic method is used to add the attributes of the class instance. For example, let's say object1 is an instance of a class A and object2 is an instance of class B and both of these classes have an attribute called 'a', that holds an integer.

What is __ ABS __ in Python?

In Python, __abs__() method is a special method that describes the absolute value of the object. You can implement this object in your custom class to define what happens when someone calls abs() on your objects. When talking about numbers, the absolute value measures the distance from 0.

How do you override a function in Python?

In Python method overriding occurs by simply defining in the child class a method with the same name of a method in the parent class. When you define a method in the object you make this latter able to satisfy that method call, so the implementations of its ancestors do not come in play.


2 Answers

__dict__ is not a special method on Python objects. It is used for the attribute dictionary; dict() never uses it.

Instead, you could support iteration; when dict() is passed an iterable that produces key-value pairs, a new dictionary object with those key-value pairs is produced.

You can provide an iterable by implementing a __iter__ method, which should return an iterator. Implementing that method as a generator function suffices:

class Foo(object):     def __init__(self, *values):         self.some_sequence = values      def __iter__(self):         for key in self.some_sequence:             yield (key, 'Value for {}'.format(key)) 

Demo:

>>> class Foo(object): ...     def __init__(self, *values): ...         self.some_sequence = values ...     def __iter__(self): ...         for key in self.some_sequence: ...             yield (key, 'Value for {}'.format(key)) ...  >>> f = Foo('bar', 'baz', 'eggs', 'ham') >>> dict(f) {'baz': 'Value for baz', 'eggs': 'Value for eggs', 'bar': 'Value for bar', 'ham': 'Value for ham'} 

You could also subclass dict, or implement the Mapping abstract class, and dict() would recognize either and copy keys and values over to a new dictionary object. This is a little more work, but may be worth it if you want your custom class to act like a mapping everywhere else too.

like image 174
Martijn Pieters Avatar answered Sep 23 '22 04:09

Martijn Pieters


No. __dict__ is a method used for introspection - it returns object attributes. What you want is a brand new method, call it as_dict, for example - that's the convention. The thing to understand here is that dict objects don't need to be necessarily created with dict constructor.

like image 26
letitbee Avatar answered Sep 21 '22 04:09

letitbee