Override dict () in class

I am trying to create a dict-like class in Python.

When you create a class, you have certain methods that tell Python how to create an inline class. For example, overriding a method __int__tells Python what to return if the user uses an int()instance of the class. The same for __float__. You can even control how Python makes iterable object of class, overriding the method __iter__(which can help to make Python listand tupleyour class). My question is: how do you tell Python how to make dictyour custom class? __dict__There is no special method , so how would you do it? I want something like the following:

class Foo():
    def __dict__(self):
        return {
            'this': 'is',
            'a': 'dict'
        }

foo = Foo()
dict(foo) # would return {'this': 'is', 'a': 'dict'}

I tried to inherit the class from dict, but it causes an error later in the code due to subclasses trying to inherit from dictand type, therefore, inheriting from is dictnot an option. Is there any other way to do this?

Also, I already redefined the method __iter__to return an object dict_keyiterator(which returns when you use iter()on dict), but it still doesn't seem like it should be.

+4
source share
2 answers

dictcan be called using iteration of pairs, so if you create your own __iter__to return the iteration of tuples, your example works as you would like:

class Foo:
    def __iter__(self):
        yield from {
            'this': 'is',
            'a': 'dict'
        }.items()

dict(Foo())
{'a': 'dict', 'this': 'is'}

, python, , , , abc.Mapping.

, __getitem__, __iter__ __len__ abc.Mapping, __getitem__, __iter__, __len__ __contains__, keys, items, values, get, __eq__ __ne__.

+2

@ForeverWintr , , , , dict.

, , , ( , , , ).

:

class Foo:
    def to_dict(self):
        return {'this': 'is', 'more': 'clear'}

print( Foo().to_dict() )  # -> {'this': 'is', 'more': 'clear'}
+1

Source: https://habr.com/ru/post/1687096/


All Articles