In python, how can I simulate a read-only property in classes?

Asked

Viewed 83 times

2

I would like to know how I can simulate a read-only property on Python.

For example, I have the following code:

class IPInfo(object):
     def __init__(self, ip):
         self.ip = ip;


ip = IPInfo(object)

ip.ip = 'aqui é possível editar, mas quero desabilitar isso';

print ip.ip #aqui é possível imprimir, pois a leitura é permitida

How could I make the property ip read-only?

  • I do not think so, I say this supported here: http://stackoverflow.com/questions/2682745/how-to-create-a-constant-in-python

  • @Miguel gives yes :p.

  • Ok, if it is with decorators gives

  • That’s right, hehehehe

1 answer

3


Declare a property getter-only, using the developer @property

class IPInfo(object):
    def __init__(self, ip):
        self._ip = ip;

    @property
    def ip (self):
        return self._ip


ip = IPInfo(object)

ip.ip = 'aqui é possível editar, mas quero desabilitar isso';
#A linha acima vai estourar um erro - AttributeError: can't set attribute    

print ip.ip
  • In case it wouldn’t be a double underline?

  • In self._ip?

  • is ...............

  • I could give a practical example jbueno sff. I tested here but do not know how to define/print the 'constant', the result I get is <property object at 0x7feaa22bb818>

  • @Wallacemaxters Actually, I don’t think so, but I’m not sure. I think following the Python naming convention, it’s a single underscore.

  • 2

    @jbueno is true. When using two, you are indicating a special functionality.

  • @Miguel Pronto, I’m trying to save a fiddle

  • Thank you jbueno

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.