Arnab Datta
Arnab Datta

Reputation: 5206

Python property to restrict access

I have the following code :

class C:
    def __init__(self, dx = 1):
       self._dx = dx
    def get_dx(self):
       return self._dx

    dx = property(get_dx,None,None)

c = C()
print c.dx
c.dx = 42
print c.dx  # this shows 42

This should work (see here). However, it is not and my questions are as follows :

  1. Is it at all possible to restrict users from doing : c.dx = 42 ?
  2. If so, how? (my intention is to make read-only attributes, I know that there is always a way to hack around it, but I just want to prevent the standard c.dx = val from working)

Upvotes: 1

Views: 2547

Answers (2)

Luka Rahne
Luka Rahne

Reputation: 10447

  class C:
    def __init__(self, dx = 1):
       self.__dx = dx
    def get_dx(self):
       return self.__dx

    dx = property(get_dx,None,None)

c = C()
print c.get_dx()
print c.__dx  # this raise error

Source: http://docs.python.org/tutorial/classes.html#private-variables

Upvotes: 0

Cat Plus Plus
Cat Plus Plus

Reputation: 129764

property with no setter defined is read-only. The only reason this might not work is that you're using Python 2 and defined an old-style class. Remember to always derive from object in Python 2.x:

class C(object):
    @property
    def dx(self):
        return self._dx

    def __init__(self, dx = 1):
        self._dx = dx

Upvotes: 4

Related Questions