@property in Python

What is @property

A normal class with class variable num:

class Item(object):

def __init__(self, value = 0):
self._num = value

Be aware: _num has no difference with num, the _ just let the variable num to be internal only.

We can call this by:

create new object
item = Item()

# set num
item.num = 10

# get num
item.num
10

Special scenarios, we don’t want customers to buy more than 100 item at a time, we might think to use property (not the @property)

class Item(object):

def __init__(self, value=0):
print "init"
self._num = value

@property
def num(self):
return self._num

@num.setter
def num(self, value):
if value > 100:
raise ValueError("Not allowed to buy more than 100 items at a time")
self._num = value


item = Item()
item.num = 1000
print item.num

It will raise an error says “ValueError: Not allowed to buy more than 100 items at a time”