可以有2个构造函数,常规的__init__
和@classmethod
Animal.get
?Python类中的两个构造函数
由于创建新对象的计算量很大,我们希望将先前创建的实例存储在类属性cls.zoo
中,如果存在,则从cls.zoo
获取实例的缓存副本。用户不会直接访问Animal.zoo
。如果用户想要获得Animal
对象,他总是会使用Animal.get()
。
这种方法是正确的/ pythonic?
我不熟悉Singleton模式。代码是否考虑使用Singleton模式?
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')
如果这是你认为工作代码可以改进,考虑[codereview.se](虽然他们会想要实际的代码,而不是一个虚拟的例子)。 – jonrsharpe
这是真实的代码吗?看起来它可能是演示/播放代码,这对Code Review来说是无关紧要的。 – Phrancis
相反,通过类方法的替代构造函数没有什么问题。 – MaxNoe