Checking for member existence in Python

前端 未结 5 1596
北恋
北恋 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:51

    A little off-topic in the way of using it. Singletons are overrated, and a "shared-state" method is as effective, and mostly, very clean in python, for example:

    class Borg:
        __shared_state = {}
        def __init__(self):
            self.__dict__ = self.__shared_state
        # and whatever else you want in your class -- that's all!
    

    Now every time you do:

    obj = Borg()
    

    it will have the same information, or, be somewhat the same instance.

提交回复
热议问题