限制 class 覆盖 python 中 class 定义中的父属性

Restrict class from overriding parent attribute inside class definition in python

我有一个基础插件定义,我正在从中创建子插件 classes。附加到应用程序的插件正在使用继承自子插件的 classes,例如 Writer。我想防止 class 更改插件的类型。

from abc import ABCMeta, abstractclassmethod

class BasePlugin(metaclass=ABCMeta):

    @property
    @abstractclassmethod
    def ID(cls):
        pass

    @property
    @abstractclassmethod
    def TYPE(cls):
        pass

    def __setattr__(self, name, value):
        if name in ['ID','TYPE']:
            raise Exception("Denied")
        else:
            object.__setattr__(self, name, value)

class Writer(BasePlugin):

    TYPE = "WRITER"

class Plugin1(Writer):
    
    ID = "plugin1"

    TYPE = "dummy type"  ## I WANT TO RESTRICT THIS

我可以限制它在实例上设置类型但不能在 class

s1 = Plugin1()
print(s1.ID)
print(s1.TYPE)
s1.ID = "n"
s1.TYPE = "newType"

很难让它防水,但一个简单的机制是:

class Writer(BasePlugin):

    TYPE = "WRITER"
    
    def __init__(self):
        if self.TYPE != "WRITER":
            raise Exception("Denied")

class Plugin1(Writer):
    
    TYPE = "dummy type"


p = Plugin1()

已经在 Plugin1 的实例化中引发了异常。但是,当您覆盖 base class Writer 的构造函数而不调用它时,可以避免这种情况。