【问题标题】:How does one create an generalise AttrDict Mixin for a python "dict-style" class?如何为python“dict-style”类创建一个泛化的 AttrDict Mixin?
【发布时间】:2016-09-19 13:04:37
【问题描述】:

基本上,我希望能够像dict(例如我下面的示例DICT)一样采用classquacks 并添加一个MixIn,它允许我访问@ 987654325@的值作为属性...例如

print purchase.price # instead of purchase["price"]

背景:我有各种不同的数据库表(不仅仅是DICT 示例),它们看起来(&quack)像dict(例如bsddb),我想定义(然后使用)标准AttrDictMixIn。 (因此避免使用样板剪切/粘贴代码)

# First try using a std dict
class AttrDict(dict):
    def __init__(self, *args, **kwargs):
        self.__dict__ = self
        super(AttrDict, self).__init__(*args, **kwargs)

test1=AttrDict()
test1.x="111"
print 1,test1

# Next derive a crude UPPER dict
class DICT(dict): # EXAMPLE ONLY
  def __getitem__(self,key):
    return super(DICT,self).__getitem__(key.upper())

  def __setitem__(self,key,value):
    return super(DICT,self).__setitem__(key.upper(),value)

test2=DICT()
test2["x"]="222"
print 2,test2

# Next define a AttrDict MixIn
class AttrDictMixIn(object):  # This is what I want to work...
    def __init__(self, *args, **kwargs):
        self.__dict__ = self
        return super(AttrDict, self).__init__(*args, **kwargs)

# Apply the MixIn to DICT 
class AttrDICT(DICT,AttrDictMixIn): pass

test3=AttrDICT()
test3.x="333.xxx"
test3["y"]="333.yyy"
print 3,test3,"X is missing"
print 4,"test3.x:",test3.x,"OK"
print 5,"test3['y']:",test3["y"],"OK"
print 6,"test3.y:",test3.y,"DUD"
print 7,"test3['x']:",test3["x"],"DUD"

输出:

1 {'x': '111'}
2 {'X': '222'}
3 {'Y': '333.yyy'} X is missing
4 test3.x: 333.xxx OK
5 test3['y']: 333.yyy OK
6 test3.y:
Traceback (most recent call last):
  File "x.py", line 39, in <module>
    print 6,"test3.y:",test3.y,"DUD"
AttributeError: 'AttrDICT' object has no attribute 'y'

我怀疑我做错了什么...欢迎提示。 (并且指向类似 python MixIns 的一些参考示例的指针也可能有所帮助)

编辑:请解释为什么self.__dict__ = self 行会破坏多重继承。

【问题讨论】:

  • 你是什么意思但它不起作用?您想发布错误的回溯吗?
  • 刚刚添加了“X is missing”注释和回溯。

标签: python class dictionary attributes multiple-inheritance


【解决方案1】:

像这样实现它:

class AttrDictMixin(object):
    def __getattr__(self, name):
        return self[name]
    def __setattr__(self, name, value):
        self[name] = value
    def __delattr__(self, name):
        del self[name]

在访问、设置或删除属性时 - 相应地调用 __getattr____setattr____delattr__

请记住,mixin 应该位于继承中的基类之前:

class AttrDict(AttrDictMixin, DICT): pass

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    • 2023-03-31
    相关资源
    最近更新 更多