Home > Back-end >  Restrict class from overriding parent attribute inside class definition in python
Restrict class from overriding parent attribute inside class definition in python

Time:04-15

I have a base plugin definition from which am creating sub plugin classes. Plugins that are attached to the app are using the classes inherited from subplugin like Writer. I want to prevent the class from changing the TYPE of plugin.

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

I am able to restrict it from setting the type on instance but not in class

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

CodePudding user response:

It is hard to make it waterproof, but a simple mechanism would be:

class Writer(BasePlugin):

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

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


p = Plugin1()

Already on the instantiation of Plugin1 the exception is raised. But this could be avoided when you overwrite the constructor of base class Writer without calling it.

  • Related