[英]implementing python metaclass for changing class level variable
Can you explain, how to implement AFactory
class for doing this. 您能否解释一下如何实现
AFactory
类。 It seems that I need to use metaclass but how? 看来我需要使用元类,但是如何使用? All my tries failed with
KeyError
我所有的尝试均因
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'
It sounds like you really want a class factory, not a metaclass. 听起来您确实想要一个类工厂,而不是一个元类。 (Yes, metaclasses are also class factories, but they're not the only ones.) So the easiest solution is to define
AFactory
as a function: (是的,元类也是类工厂,但不是唯一的类。)因此,最简单的解决方案是将
AFactory
定义为一个函数:
def AFactory(name):
class A:
NAME = name
VARIABLE = dct[NAME]
return A
If you really need a metaclass, you should implement an alternative constructor rather than trying to make the metaclass callable as AFactory(name)
: 如果您确实需要一个元类,则应该实现一个替代的构造函数,而不是尝试使该元类可调用为
AFactory(name)
:
class AFactory(type):
@classmethod
def make(mcs, name):
clsname = 'A'
bases = ()
attrs = {
'NAME': name,
'VARIABLE': dct[name]
}
return mcs(clsname, bases, attrs)
Which you could then use like 然后您可以使用像
A1 = AFactory.make('key1')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.