0

Trying to understand private/public attributes for a class I started to play with @property. I don't get why when I define a class like this:

class Number(object):

    @property
    def num1(self):
        return self._num1

    @num1.setter
    def num1(self, i):
        if i < 5:
            raise ValueError("Small number!")
        self._num1 = i

When I create an object using such class and set values for var num1like this:

def testNumber():
    number = Number()
    number.num1 = 22
    number._num1=2
    print number._num1
    print number.num1

That will output 2 for num1 and _num1, avoiding the @property set for num1. Now if I set num1 with a lower value than 5 the exception is raised. How does this work for Pyhton? (no need to add that I'm new at Python)

Cong Ma
  • 10,692
  • 3
  • 31
  • 47
Nick_
  • 11
  • 1
  • 4
  • Why would you expect the setter for num1 to be executed when you set _num1? – Patrick Maupin Sep 19 '15 at 19:49
  • Not sure what your question is. Are you asking why the exception is not raised when you set `_num1` directly? – BrenBarn Sep 19 '15 at 19:52
  • Patrick/BrenBarn I was trying to understand why I have acess to num1 using _num1 sorting the setter defined for num1. There's something about access that I'm still trying to understand. So far, I believed that setting a property over an attribute then I wont be able to modfy it directly anymore. I don't understand the "_" before a variable. Is it a class variable? However, I read the link you shared Patrick and it clarified me everything. Thanks a lot guys! – Nick_ Sep 19 '15 at 20:01

0 Answers0