这段代码允许您使用
名称和参数名称。
__init__中的参数验证不允许
未知参数,如果需要其他验证,如
输入,或者它们是必需的,只需添加逻辑
在那里:class BaseClass(object):
def __init__(self, classtype):
self._type = classtype
def ClassFactory(name, argnames, BaseClass=BaseClass):
def __init__(self, **kwargs):
for key, value in kwargs.items():
# here, the argnames variable is the one passed to the
# ClassFactory call
if key not in argnames:
raise TypeError("Argument %s not valid for %s"
% (key, self.__class__.__name__))
setattr(self, key, value)
BaseClass.__init__(self, name[:-len("Class")])
newclass = type(name, (BaseClass,),{"__init__": __init__})
return newclass
它的工作原理如下,例如:>>> SpecialClass = ClassFactory("SpecialClass", "a b c".s