您能解释一下如何实现AFactory
类吗?看来我需要使用元类,但是如何使用?我所有的尝试都因KeyError
dct = {
'key1': 'value1',
'key2': 'value2'
}
class AFactory:
pass
class A:
NAME = ''
VARIABLE = dct[NAME]
A1 = AFactory('key1')
a1 = A1()
assert a1.NAME == 'key1'
assert a1.VARIABLE == 'value1'
A2 = AFactory('key2')
a2 = A2()
assert a2.NAME == 'key2'
assert a2.VARIABLE == 'value2'
答案 0 :(得分:2)
听起来您真的想要一个类工厂,而不是一个元类。 (是的,元类也是类工厂,但不是唯一的类工厂。)因此,最简单的解决方案是将AFactory
定义为一个函数:
def AFactory(name):
class A:
NAME = name
VARIABLE = dct[NAME]
return A
如果您确实需要一个元类,那么您should implement an alternative constructor而不是尝试使该元类可调用为AFactory(name)
:
class AFactory(type):
@classmethod
def make(mcs, name):
clsname = 'A'
bases = ()
attrs = {
'NAME': name,
'VARIABLE': dct[name]
}
return mcs(clsname, bases, attrs)
然后您可以使用like
A1 = AFactory.make('key1')