加载中...

9.13 使用元类控制实例的创建


问题

你想通过改变实例创建方式来实现单例、缓存或其他类似的特性。

解决方案

Python程序员都知道,如果你定义了一个类,就能像函数一样的调用它来创建实例,例如:

  1. class Spam:
  2. def __init__(self, name):
  3. self.name = name
  4. a = Spam('Guido')
  5. b = Spam('Diana')

如果你想自定义这个步骤,你可以定义一个元类并自己实现 __call__() 方法。

为了演示,假设你不想任何人创建这个类的实例:

  1. class NoInstances(type):
  2. def __call__(self, *args, **kwargs):
  3. raise TypeError("Can't instantiate directly")
  4. # Example
  5. class Spam(metaclass=NoInstances):
  6. @staticmethod
  7. def grok(x):
  8. print('Spam.grok')

这样的话,用户只能调用这个类的静态方法,而不能使用通常的方法来创建它的实例。例如:

  1. >>> Spam.grok(42)
  2. Spam.grok
  3. >>> s = Spam()
  4. Traceback (most recent call last):
  5. File "<stdin>", line 1, in <module>
  6. File "example1.py", line 7, in __call__
  7. raise TypeError("Can't instantiate directly")
  8. TypeError: Can't instantiate directly
  9. >>>

现在,假如你想实现单例模式(只能创建唯一实例的类),实现起来也很简单:

  1. class Singleton(type):
  2. def __init__(self, *args, **kwargs):
  3. self.__instance = None
  4. super().__init__(*args, **kwargs)
  5. def __call__(self, *args, **kwargs):
  6. if self.__instance is None:
  7. self.__instance = super().__call__(*args, **kwargs)
  8. return self.__instance
  9. else:
  10. return self.__instance
  11. # Example
  12. class Spam(metaclass=Singleton):
  13. def __init__(self):
  14. print('Creating Spam')

那么Spam类就只能创建唯一的实例了,演示如下:

  1. >>> a = Spam()
  2. Creating Spam
  3. >>> b = Spam()
  4. >>> a is b
  5. True
  6. >>> c = Spam()
  7. >>> a is c
  8. True
  9. >>>

最后,假设你想创建8.25小节中那样的缓存实例。下面我们可以通过元类来实现:

  1. import weakref
  2. class Cached(type):
  3. def __init__(self, *args, **kwargs):
  4. super().__init__(*args, **kwargs)
  5. self.__cache = weakref.WeakValueDictionary()
  6. def __call__(self, *args):
  7. if args in self.__cache:
  8. return self.__cache[args]
  9. else:
  10. obj = super().__call__(*args)
  11. self.__cache[args] = obj
  12. return obj
  13. # Example
  14. class Spam(metaclass=Cached):
  15. def __init__(self, name):
  16. print('Creating Spam({!r})'.format(name))
  17. self.name = name

然后我也来测试一下:

  1. >>> a = Spam('Guido')
  2. Creating Spam('Guido')
  3. >>> b = Spam('Diana')
  4. Creating Spam('Diana')
  5. >>> c = Spam('Guido') # Cached
  6. >>> a is b
  7. False
  8. >>> a is c # Cached value returned
  9. True
  10. >>>

讨论

利用元类实现多种实例创建模式通常要比不使用元类的方式优雅得多。

假设你不使用元类,你可能需要将类隐藏在某些工厂函数后面。比如为了实现一个单例,你你可能会像下面这样写:

  1. class _Spam:
  2. def __init__(self):
  3. print('Creating Spam')
  4. _spam_instance = None
  5. def Spam():
  6. global _spam_instance
  7. if _spam_instance is not None:
  8. return _spam_instance
  9. else:
  10. _spam_instance = _Spam()
  11. return _spam_instance

尽管使用元类可能会涉及到比较高级点的技术,但是它的代码看起来会更加简洁舒服,而且也更加直观。

更多关于创建缓存实例、弱引用等内容,请参考8.25小节。


还没有评论.