Python-关于工厂函数的问题 [英] Python - question about factory functions

查看:76
本文介绍了Python-关于工厂函数的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列要注册为更高级别抽象类的服务的类.高级别的类将具有根据 init args等获取低级别的类的功能.这听起来有点疯吗?另外,这叫什么?我称它为工厂函数/类,但我真的不知道(这使得Google最佳做法更难).

I have a series of classes that I'll be registering as services to a higher level abstraction class. The high-level class will have a function that gets the lower level class based on init args, etc. Does this sound berserk? Also, what is this called? I call it factory function/class, but I really have no idea (which makes it harder to Google best practices).

推荐答案

它称为元类编程".在最新版本的Python中,它是通过定义 __new__() 静态方法来实现的并返回适当类型的对象.

It's called "metaclass programming". In recent versions of Python it's implemented by defining the __new__() static method and returning an object of the appropriate type.

class C(object):
  def __new__(cls, val):
    if val == 5:
      return 'five'
    else:
      return super(C, cls).__new__(cls)

c1 = C(3)
print c1
c2 = C(5)
print c2

这篇关于Python-关于工厂函数的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆