有两个构造函数,正则的__init__
和@classmethod
Animal.get
可以吗?你知道吗
由于创建一个新对象是计算密集型的,因此我们希望将以前创建的实例存储在类属性cls.zoo
中,并从cls.zoo
获取实例的缓存副本(如果存在)。你知道吗
用户不会直接访问Animal.zoo
。如果用户想要获得Animal
对象,他将始终使用Animal.get()
。你知道吗
这种方法合适吗?你知道吗
我不熟悉单例模式。代码是否考虑使用单例模式?你知道吗
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')
这取决于您是只想允许类的用户访问缓存对象,还是想强制它只访问该缓存对象。有了您的解决方案,用户总是可以使用
tiger2 = Animal('tiger', 0)
来获取另一个实例。你知道吗如果确实只需要一个实例,可以使用
__new__
:以下是您只能创建一个实例的证明:
相关问题 更多 >
编程相关推荐