Python - question about factory functions

此生再无相见时 提交于 2020-01-06 05:23:13

问题


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).


回答1:


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


来源:https://stackoverflow.com/questions/3900896/python-question-about-factory-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!