问题描述
我已经开始使用这样的结构:
I've started to use constructs like these:
class DictObj(object):
def __init__(self):
self.d = {}
def __getattr__(self, m):
return self.d.get(m, None)
def __setattr__(self, m, v):
super.__setattr__(self, m, v)
在这个线程,我修改了DictObj实现为:
Update: based on this thread, I've revised the DictObj implementation to:
class dotdict(dict):
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
class AutoEnum(object):
def __init__(self):
self.counter = 0
self.d = {}
def __getattr__(self, c):
if c not in self.d:
self.d[c] = self.counter
self.counter += 1
return self.d[c]
其中DictObj是可以通过点符号访问的字典:
where DictObj is a dictionary that can be accessed via dot notation:
d = DictObj()
d.something = 'one'
发现它比美观更美观 d ['something']
。请注意,访问未定义的键将返回None而不是引发异常,这也很好。
I find it more aesthetically pleasing than d['something']
. Note that accessing an undefined key returns None instead of raising an exception, which is also nice.
更新:Smashery是一个好点,mhawke扩展了一个更容易的解决方案。我想知道是否有任何不良的副作用使用 dict 而不是定义一个新的字典;
Update: Smashery makes a good point, which mhawke expands on for an easier solution. I'm wondering if there are any undesirable side effects of using dict instead of defining a new dictionary; if not, I like mhawke's solution a lot.
AutoEnum是一个自动递增的Enum,使用像这样:
AutoEnum is an auto-incrementing Enum, used like this:
CMD = AutoEnum()
cmds = {
"peek": CMD.PEEK,
"look": CMD.PEEK,
"help": CMD.HELP,
"poke": CMD.POKE,
"modify": CMD.POKE,
}
两个都对我很好,但我对他们感到不爽。
Both are working well for me, but I'm feeling unpythonic about them.
这些实际上是不好的结构吗?
Are these in fact bad constructs?
推荐答案
DictObj类的简单版本:
This is a simpler version of your DictObj class:
class DictObj(object):
def __getattr__(self, attr):
return self.__dict__.get(attr)
>>> d = DictObj()
>>> d.something = 'one'
>>> print d.something
one
>>> print d.somethingelse
None
>>>
这篇关于字典键unpythonic的Javascript风格点符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!