0

I've been working on a personal project for quite some time now, but I've found myself stuck on a particular problem: I would like only the first instance of a Class to define the attribute for all future instances of the Class. However I don't want to store this in a global variable outside of my code because it gets in the way of something else. How can I do this? What I've thought of for now (and implemented) is to have a counter that checks if this is the first instance of the Class, however where can I store this value? Thanks!!

1 Answers1

0

This sounds like you are asking about singletons. These classes are objects that limit the number of times an object can be initialised to 1. Every other call will just return the same object.

To create a singleton, you simply need to edit the __new__ function and change how it is run.

class SingletonClass(object):
  def __new__(cls):
    if not hasattr(cls, 'instance'):
      cls.instance = super(SingletonClass, cls).__new__(cls)
    return cls.instance
   
class SingletonChild(SingletonClass):
    pass

EDIT: Better example

ItzTheDodo
  • 100
  • 8
  • Hmm I see - is there a way to do this directly in the constructor of my main class? Or right before? – badcoder123 Apr 13 '22 at 06:20
  • There are many methods to create a singleton but all will require you to edit this function. This post from a few years ago has much of the information you may need: https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python?rq=1 – ItzTheDodo Apr 13 '22 at 06:24