Checking for member existence in Python

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

    I just tried to measure times:

    class Foo(object):
        @classmethod
        def singleton(self):
            if not hasattr(self, 'instance'):
                self.instance = Foo()
            return self.instance
    
    
    
    class Bar(object):
        @classmethod
        def singleton(self):
            try:
                return self.instance
            except AttributeError:
                self.instance = Bar()
                return self.instance
    
    
    
    from time import time
    
    n = 1000000
    foo = [Foo() for i in xrange(0,n)]
    bar = [Bar() for i in xrange(0,n)]
    
    print "Objs created."
    print
    
    
    for times in xrange(1,4):
        t = time()
        for d in foo: d.singleton()
        print "#%d Foo pass in %f" % (times, time()-t)
    
        t = time()
        for d in bar: d.singleton()
        print "#%d Bar pass in %f" % (times, time()-t)
    
        print
    

    On my machine:

    Objs created.
    
    #1 Foo pass in 1.719000
    #1 Bar pass in 1.140000
    
    #2 Foo pass in 1.750000
    #2 Bar pass in 1.187000
    
    #3 Foo pass in 1.797000
    #3 Bar pass in 1.203000
    

    It seems that try/except is faster. It seems also more readable to me, anyway depends on the case, this test was very simple maybe you'd need a more complex one.

提交回复
热议问题