Python access modifiers as a decorator

  Kiến thức lập trình

In python, _name is protected and __name is private

Is it possible to implement access modifiers for classes with decorators? How?

The functionality should be like the code below:

class A:
    
    def public(self):
        self.protected()    # Runs without warning and error    (Because is called in the owner class)
        self.private()      # Runs without warning and error    (Because is called in the owner class)
    
    @protected
    def protected(self):
        print('protected is running')
        self.private()      # Runs without warning and error    (Because is called in the owner class)
    
    @private
    def private(self):
        print(f'private is running')


a = A()
a.public()                  # Runs without any warning and error            (Because has no access modifier)
a.protected()               # Runs with protected warning
a.private()                 # Raises Exception

LEAVE A COMMENT