这个Python模式有什么“尴尬”吗? [英] Are there any 'gotchas' with this Python pattern?
问题描述
这里是我想使用的模式:
class Dicty(dict):
def __init __ self):
self .__ dict__ = self
d = Dicty()
d.foo ='bar'
print d ['foo']
>>>> bar
d ['foo'] ='baz'
print d.foo
>>>> 'baz'
通常,我喜欢通过dict get / set访问的对象属性访问的语义,在某些情况下需要使用类似dict的访问(例如, d ['foo-bar'] ='baz'
),我不想有特殊这些情况下的吸气剂设定器方法,因此,对象与共享属性同时。
有上述模式的任何陷阱吗?
更少的hacky方式来实现相同的效果:
class Dicty(dict):
pre>
def __getattr __ ,key):
return self [key]
def __setattr __(self,key,value):
self [key] = value
我认为你的方式也可以正常工作,但设置
__ dict __
属性,似乎有点iffy风格,如果任何人最终读取你的代码,必然会引起一些问题。Here's the pattern I'm thinking of using:
class Dicty(dict): def __init__(self): self.__dict__ = self d = Dicty() d.foo = 'bar' print d['foo'] >>> bar d['foo'] = 'baz' print d.foo >>> 'baz'
Generally, I prefer the semantics of object attribute access over dict get/set access, but there are some circumstances where dict-like access is required (for example,
d['foo-bar'] = 'baz'
) and I'd prefer not to have special getter setter methods for these cases, so thus, the dual behavior of dict & object at the same time with shared attributes.Are there any gotchas with the above pattern?
解决方案Here's a less "hacky" way to achieve the same effect:
class Dicty(dict): def __getattr__(self, key): return self[key] def __setattr__(self, key, value): self[key] = value
I think that your way may work fine as well, but setting the
__dict__
attribute like that seems a bit iffy style-wise, and is bound to raise some questions if anyone else ends up reading your code.这篇关于这个Python模式有什么“尴尬”吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!