I want to share an utility object across my whole project without instantiating it more than once. It's basically something like a logger, database connection or browser window. I want the same object id in any instance of any class alive.
In my understanding that is what class variables are used for, but when I declare my utilities as a class variable within my parent class, it's being instantiated as soon as the parent class is being called the first time. That's not what I want. I want it to be initiated by hand, but I do not want to initialize it again every time a child is born while the new born child should be able to use it.
My design looks like this:
Utility class
class Utils:
def utility_1(self):
print("Do something")
Parent class
class Parent:
utility = Utils.utility_1()
Child class
class Child(Parent):
def __init__(self, x):
self.x = x
def use_utility_1(self):
self.utility_1(self.x)
The parent class as well as child class need to be able to use it. Everything I read about decorators etc. is going beyond or a are not the thing I need - at least in my understanding.
CodePudding user response:
Your code in your question is unclear, but just going on your description:
class Parent:
utility = Utils() # A single instantiation here
class Child(Parent):
def __init__(self, x):
self.x = x
def use_utility_1(self):
self.utility.utility_1() #Prints Do Something
CodePudding user response:
Based on my understanding, what you want with the Utils
object is a singleton, which is probably the cleanest way of implementing what you want. To read about how to implement that in Python3 you can have a look at an example here.
Notice that in the code of your Parent
class you are not instantiating the Utility object, rather you are assigning the return value of Utils.utility_1
to utility
. What you probably wanted to do is:
class Parent:
utils = Utils()
In this way you can call the utility function both from the Parent class and on the Parent and Child objects:
class Utils:
def log(self, x):
print("This is x:", x)
class Child(Parent):
def __init__(self, x):
self.x = x
def use_logger(self):
self.utils.log(self.x)
Input:
child1 = Child("hello")
child1.use_logger()
child2 = Child("world")
child2.use_logger()
Parent.utils.log("hey there")
a_parent = Parent()
a_parent.utils.log("sup"
Output:
This is x: hello
This is x: world
This is x: hey there
This is x: sup
However, using static variables of a class does not allow you to instantiate them by hand.