Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensure that only one instance of a class gets run

I have an underlying class which I want to place in some code. I only want it to be instantiated or started once for a given app although it might be called many times.. The problem with the code below is that LowClass is started over and over again. I only want it to start once per test..

import logging

class LowClass:

    active = False

    def __init__(self):
        self.log = logging.getLogger()
        self.log.debug("Init %s" % self.__class__.__name__)
        if self.active:
            return
        else:
            self.active = True
        self.log.debug("Now active!")

class A:
    def __init__(self):
        self.log = logging.getLogger()
        self.log.debug("Init %s" % self.__class__.__name__)
        self.lowclass = LowClass()

class B:
    def __init__(self):
        self.log = logging.getLogger()
        self.log.debug("Init %s" % self.__class__.__name__)
        self.lowclass = LowClass()

class C:
    def __init__(self):
        self.log = logging.getLogger()
        self.log.debug("Init %s" % self.__class__.__name__)
        self.a = A()
        self.b = B()


class ATests(unittest.TestCase):
    def setUp(self):
        pass

    def testOne(self):
        a = A()
        b = B()

    def testTwo(self):
        c = C()

Thanks for pointing out my problem!!

like image 437
rh0dium Avatar asked Oct 15 '09 23:10

rh0dium


People also ask

What is __ new __ in Python?

The __new__() is a static method of the object class. It has the following signature: object.__new__(class, *args, **kwargs) Code language: Python (python) The first argument of the __new__ method is the class of the new object that you want to create.

How do you instantiate a class in python?

In short, Python's instantiation process starts with a call to the class constructor, which triggers the instance creator, . __new__() , to create a new empty object. The process continues with the instance initializer, . __init__() , which takes the constructor's arguments to initialize the newly created object.


1 Answers

See singleton in python.

like image 125
Ewan Todd Avatar answered Sep 22 '22 10:09

Ewan Todd