python实现封闭类(禁止继承),python封闭,python没有seal
python实现封闭类(禁止继承),python封闭,python没有seal
python没有sealed或者final的关键字,不过我们可以通过__init__来实现禁止继承。
class terminal(type): def __init__(self, cl_name, bases, namespace): for cls in bases: if isinstance(cls, terminal): raise TypeError("in "+cl_name+" definition : "+str(cls)+ " can't be used as a base class") super(terminal, self).__init__(cl_name, bases, namespace)# first we create a normal classclass a(object): pass#the terminal class: it can inherit from other classes but can't be#used as base classclass b(a): __metaclass__= terminal#this will fail at compile time, because inheriting from b is forbiddenclass c(b): pass
这里使用metaclass来实现封闭类的,在__init__方法中会挨个检查基类看是否是不可继承的,如果不可继承就会抛出TypeError异常。
相关内容
- python里的列表list使用范例代码,python范例,#list#新建列
- python winreg 示例,pythonwinreg,下面是关于_winreg
- python连接sql server数据库,pythonsql,首先,到http://p
- Basic synchronization decorator,,下面代码是对python
- 初学python,,初学python[Pyt
- python实现多线程下载,python实现多线程,python实现多线程
- 金山快盘自动签到程序,金山签到程序,自动签到领取积
- python多线程Ping网段,python多线程ping,通过修改本站一个
- python用多个分隔符拆分字符串,python分隔符,如下代码,
- python计算指定两点经纬度之间的距离,python经纬度,下面
评论关闭