python根据一个基类生成派生类_如何从基类动态创建派生类

这段代码允许您使用

名称和参数名称。

__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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值