Is it OK to have 2 constructor functions, the regular __init__
and a @classmethod
Animal.get
?
Since creating a new object is computationally intensive, we want to store previously created instances in a class attribute cls.zoo
and get a cached copy of the instance from cls.zoo
if it exists.
The user will not access Animal.zoo
directly. If the user wants to get an Animal
object, he will always use Animal.get()
.
Is this approach proper/pythonic?
I'm not familiar with the Singleton Pattern. Is the code considered using the Singleton Pattern?
class Animal:
zoo = {}
# will not be called directly from outside the class
def __init__(self, species ,age):
self.species = species
self.age = age
self.runExpensiveFunction()
# User alway use this function
@classmethod
def get(cls, species):
if species in cls.zoo:
animal = cls.zoo[species]
else:
animal = Animal(species, 0)
cls.zoo[species] = animal
return animal
tiger = Animal.get('tiger')
bear = Animal.get('bear')