Javascript style dot notation for dictionary keys unpythonic?

前端 未结 12 1042
刺人心
刺人心 2020-12-23 10:44

I\'ve started to use constructs like these:

class DictObj(object):
    def __init__(self):
        self.d = {}
    def __getattr__(self, m):
        return s         


        
12条回答
  •  悲&欢浪女
    2020-12-23 11:00

    Your DictObj example is actually quite common. Object-style dot-notation access can be a win if you are dealing with ‘things that resemble objects’, ie. they have fixed property names containing only characters valid in Python identifiers. Stuff like database rows or form submissions can be usefully stored in this kind of object, making code a little more readable without the excess of ['item access'].

    The implementation is a bit limited - you don't get the nice constructor syntax of dict, len(), comparisons, 'in', iteration or nice reprs. You can of course implement those things yourself, but in the new-style-classes world you can get them for free by simply subclassing dict:

    class AttrDict(dict):
        __getattr__ = dict.__getitem__
        __setattr__ = dict.__setitem__
        __delattr__ = dict.__delitem__
    

    To get the default-to-None behaviour, simply subclass Python 2.5's collections.defaultdict class instead of dict.

提交回复
热议问题