Checking for member existence in Python

前端 未结 5 1580
北恋
北恋 2020-12-01 14:23

I regularly want to check if an object has a member or not. An example is the creation of a singleton in a function. For that purpose, you can use hasattr like

5条回答
  •  时光说笑
    2020-12-01 14:34

    I have to agree with Chris. Remember, don't optimize until you actually need to do so. I really doubt checking for existence is going to be a bottleneck in any reasonable program.

    I did see http://code.activestate.com/recipes/52558/ as a way to do this, too. Uncommented copy of that code ("spam" is just a random method the class interface has):

    class Singleton:
        class __impl:
            def spam(self):
                return id(self)
        __instance = None
        def __init__(self):
            if Singleton.__instance is None:
                Singleton.__instance = Singleton.__impl()
            self.__dict__['_Singleton__instance'] = Singleton.__instance
        def __getattr__(self, attr):
            return getattr(self.__instance, attr)
        def __setattr__(self, attr, value):
            return setattr(self.__instance, attr, value)
    

提交回复
热议问题