Yao Hsiao
Yao Hsiao
Jul 30, 2017 · 2 min read

I am attending a Python study group this semester, and this is the note for the last week’s meeting, which I was the main speaker. Beside, we are reading Python Cookbook.

1. Property v.s Attribute
Attributes are objects defined in the class. (e.g int age in a class Person) Properties are a special kind of attribute.

2. Why and When to use ‘Property’ ?
Technically, we can “CUSTOMIZE” access to an attribute when we define it as a property.
Anyway, consider the circumstance below:

You need a “validation” for the temperature after seeing someone use the code with improper temperature such as -300, which is below -273, the absolute zero. So you may add the following methods for validation.

Since c.temperature = num now deprecates, we should change all c.temperature = num` to c.set_temperature(num) in our originally code ?!?!????!!!!

NO!! Here comes the magic of property function.

We now makes ‘temperature’ a property attribute instead of an attribute by defining it with property(fget=None, fset=None, fdel=None, doc=None), a build-in function creating and returning a property object

Other ways to declare a property attribute:

3. Facts about `property()` function

(1) Its main goal: bundle a group of functions, just like bundle get_temperature and set_temperature together. Thus not necessarily should it be used within class scope.

For example,

(2) `property` actually is pretty low-level manipulation of the class in Python, since it directly manipulates self.__dict__. In other words, calling property attribute no longer invokes the search in self.__dict__ but invokes the code attached to the attribute. (i.e self.temperature -> invokes code attached to it, including get_temperature, set_temperature).(3) A way to save memory

(3)A way to save memory

4. Reference

* https://www.programiz.com/python-programming/property

* http://stackoverflow.com/questions/7374748/whats-the-difference-between-a-python-property-and-attribute