I'm trying to make a dict-like class in Python.
When you make a class, you have certain methods that tell Python how to make a built-in class. For example, overriding the __int__ method tells Python what to return if the user uses int() on an instance of the class. Same for __float__. You can even control how Python would make an iterable object of the class by overriding the __iter__ method (which can help Python make lists and tuples of your class). My question is how would you tell Python how to make a dict of your custom class? There is no special __dict__ method, so how would you go about doing 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've tried making the class inherit from dict, but it raises an error later in the code because of subclasses trying to inherit from dict and type, so inheriting from dict isn't a possibility. Is there any other way to do it?
Also, I've overridden the __iter__ method already so that it would return a dict_keyiterator object (what gets returned when you use iter() on a dict), but it still doesn't seem to work how it should.