在python中实现final类

2019-11-21 22:33:55 浏览数 (2)

当然要利用下metaclass做手脚啦

代码语言:javascript复制
class Final(type):
    def __new__(cls, name, bases, classdict):
        for b in bases:
            if isinstance(b, Final):
                raise TypeError("type '{0}' is Final type".format(b.__name__))
        return type.__new__(cls, name, bases, dict(classdict))


class Hi(object):
    def hi(self):
        print("hi")


class SubHi(Hi, metaclass=Final):
    pass

# 这个没问题
s = SubHi()
s.hi()

# TypeError: type 'SubHi' is Final type
class SubHi2(SubHi):
    pass

0 人点赞