Uwe_98
Uwe_98

Reputation: 919

Python 3.6 How do I create a Singleton with attributes and methods

all the examples shown just explain how to create a singleton of a class without the instantiation of any members.

But how can I produce a singleton of the following class in Python 3:

class NotOneOnly:

    def __init__(self, a, b):
        print("Instatiation of objects.")
        self.a = a
        self.b = b

    def run(self):
        print("Variable a = " + str(self.a) + " and variable b = " + 
str(self.b))

In the main program, the use would be:

not_one_only = NotOneOnly(5, 10)
not_one_only.run()

Thanks 4 help.

Upvotes: 0

Views: 1395

Answers (1)

Uwe_98
Uwe_98

Reputation: 919

After investigating a little bit, I've discovered this. So my conclusion is:

class OneOnly:
    _singleton = None
    a = None
    b = None

    def __new__(cls, a, b):
        if not cls._singleton:
            print("Object is created and the variables are instantiated.")
            cls._singleton = super(OneOnly, cls).__new__(cls)
            cls.a = a
            cls.b = b
        else:
            print("Sorry, byt object is already made.")
        return cls._singleton

    def run(self):
        print("Variable a = " + str(self.a) + " and variable b = " + str(self.b))

Now in the mainfile I made the following experiments showing that the singleton was created in the right way:

print("Singleton Experiment:")
a = 10
b = 5
one_only1 = OneOnly(a, b)
print(one_only1)
one_only1.run()
one_only2 = OneOnly(1, 2)
print(one_only2)
one_only2.run()
one_only1.a = 100
one_only1.run()
one_only2.run()

Now the output is:

Singleton Experiment:
Object is created and the variables are instantiated.
<__main__.OneOnly object at 0x7fa4295cbcc0>
Variable a = 10 and variable b = 5
Sorry, byt object is already made.
<__main__.OneOnly object at 0x7fa4295cbcc0>
Variable a = 10 and variable b = 5
Variable a = 100 and variable b = 5
Variable a = 100 and variable b = 5

Upvotes: 2

Related Questions