pentanol
pentanol

Reputation: 419

How to create Setters and Getters that accept arguments in Python classes

I have the following situation, A class A with a single field x. I want to create a getter and a setter for the x attribute.

class A:
    def __init__(self,x):
        self.x = x

   @property
   def x(self):
       self.x = x

   @x.setter
   def setX(self,x):
       self.x = x

   

The thing I want to add if that I want to restrict accessing and modifying my 'x' to people who have a password that I specify beforehand. Passing this password as an argument to property getters and setters in not possible in python. How to solve this encapsulation problem while still having the full control of access over my attributes?

Upvotes: 0

Views: 394

Answers (2)

pentanol
pentanol

Reputation: 419

The solution is to give up using the @property decorator and use the more traditional way that follows:

class X:
  def __init__(self,x):
    self.__x = x

  def get_x(self,password = None):
    if password and password == 'somepassword':
      return self.__x
    else:
      print('You dont have the authorization to access this info')

  def set_x(self,nx):
    self.__x = nx

Upvotes: 0

sarartur
sarartur

Reputation: 1228

Try this:

from functools import wraps

def auth_required(func):
    @wraps(func)
    def wrapper(self, *args, **kwargs):
        if not self._authenticated:
            raise Exception("Must be authenticated")
        return func(self, *args, **kwargs)
    return wrapper

class A:
    def __init__(self, x, password) :
        self._x = x
        self._password = password
        self._authenticated = False

    def authenticate(self, password):
        if password == self._password:
            self._authenticated = True

    @property
    @auth_required
    def x(self):
        return self._x

    @x.setter
    @auth_required
    def x(self,x):
        self._x = x

a = A(x = "testing", password = "sample_password")
a.x
a.x = 'testing'

output:

Exception: Must be authenticated

You can then authenticate with:

a.authenticate(password = "sample_password")
print(a.x)

Keep in mind that whatever password you store will always be visible to anyone working with the class. There is no way to avoid that.

Upvotes: 3

Related Questions