Javascript style dot notation for dictionary keys unpythonic?

前端 未结 12 1048
刺人心
刺人心 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 10:55

    It's not "wrong" to do this, and it can be nicer if your dictionaries have a strong possibility of turning into objects at some point, but be wary of the reasons for having bracket access in the first place:

    1. Dot access can't use keywords as keys.
    2. Dot access has to use Python-identifier-valid characters in the keys.
    3. Dictionaries can hold any hashable element -- not just strings.

    Also keep in mind you can always make your objects access like dictionaries if you decide to switch to objects later on.

    For a case like this I would default to the "readability counts" mantra: presumably other Python programmers will be reading your code and they probably won't be expecting dictionary/object hybrids everywhere. If it's a good design decision for a particular situation, use it, but I wouldn't use it without necessity to do so.

提交回复
热议问题