在类上重写dict() [英] Override dict() on class

查看:144
本文介绍了在类上重写dict()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Python中创建类似dict的类.

I'm trying to make a dict-like class in Python.

创建类时,您可以使用某些方法来告诉Python如何创建内置类.例如,重写__int__方法将告诉Python如果用户在类的实例上使用int(),则返回什么内容.与__float__相同.您甚至可以通过重写__iter__方法(它可以帮助Python创建类的listtuple)来控制Python如何使该类成为可迭代的对象.我的问题是,您如何告诉Python如何创建自定义类的dict?没有特殊的__dict__方法,那么您将如何去做呢?我想要以下内容:

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'}

我尝试使类从dict继承,但是由于子类试图从dicttype继承,因此稍后在代码中引发错误,因此从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?

此外,我已经覆盖了__iter__方法,以便它将返回dict_keyiterator对象(当您在dict上使用iter()时返回的内容),但它似乎仍然没有按照应有的方式工作.

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.

推荐答案

c0> 可以使用成对的可迭代对象进行调用,因此,如果您设计__iter__以返回可迭代的元组,则示例将按照您的意愿进行工作:

dict can be called with an iterable of pairs, so if you design your __iter__ to return an iterable of tuples, your example works as you'd like:

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

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


如果您希望类的行为像python字典一样,即在实例上进行迭代,则在其键上进行迭代,则可以实现


If you want your class to behave like a python dictionary, in that iterating over an instance iterates over its keys, you can implement the interface defined by abc.Mapping.

您可以通过实现__getitem____iter____len__并从abc.Mapping继承,或者通过实现所有__getitem____iter____len__ __contains__来做到这一点, keysitemsvaluesget__eq____ne__.

You can do this either by implementing __getitem__, __iter__, and __len__, and inheriting from abc.Mapping, or by implementing all of __getitem__, __iter__, __len__ __contains__, keys, items, values, get, __eq__, and __ne__.

这篇关于在类上重写dict()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆