Python @property

You will learn Python @property; Pythonic way to use collectors and definers.


Table of Contents

  • An Example To Begin With
  • Using Getters and Setters
  • The Power of @property
  • Digging Deeper into Property
Python has a concept called great treasure that makes the life of an object-oriented programmer too simple.
Before entering the definition and detailed about what @property is, we will first build an intuition about why it would be necessary in the first place.

An Example To Begin With:


Let's assume that you decide to make a class that can maintain the temperature in degrees Celsius. The method to change the air in degrees Fahrenheit will also be applied. One way to do this is.

class Celsius
  def __init__(self, temperature = 0):
  self.temperature = temperature
  def to_fahrenheit(self):
       return (self.temperature * 1.8) + 32

We can distinguish the objects of this class and manipulate temperature attributes as we would have liked. Try this on the Python shell.

>>> # create new object
>>> man = Celsius()
>>> # set temperature
>>> man.temperature = 37
>>> # get temperature
>>> man.temperature
37
>>> # get degrees Fahrenheit
>>> man.to_fahrenheit()
98.60000000000001

Therefore, internal man.temperature is receiving .__ dict __ ['temperature'].
Now, let's suppose, in addition, that we have a class that is very popular with customers and they started using it in their program. They all kinds of tasks that are opposed.

>>> man.__dict__
{'temperature': 37}

One fateful day, a trusted customer came to us and suggested that the air can not go below -273 degrees Celsius (the thermodynamic students could argue that it is actually -273.15), called absolute zero. Next, he asked us to apply the value of this restriction. For a company that strives for customer satisfaction, they happily followed the advice and released version 1.01 (update of the class people).

Using Getters and Setters:


An obvious solution to the above restrictions will be to hide the air (that private) and establish a new interface get and set to manipulate it. This can be done as follows.

class Celsius:
    def __init__(self, temperature = 0):
        self.set_temperature(temperature)

    def to_fahrenheit(self):
        return (self.get_temperature() * 1.8) + 32

    # new update
    def get_temperature(self):
        return self._temperature

    def set_temperature(self, value):
        if value < -273:
            raise ValueError("Temperature below -273 is not possible")
        self._temperature = value

We can see above that the new methods get_temperature () and set_temperature () are defined below, the air is replaced by _Temperature. An underscore (_) is initially used to denote variables in private Python.

>>> c = Celsius(-277)
Traceback (most recent call last):
...
ValueError: Temperature below -273 is not possible
>>> c = Celsius(37)
>>> c.get_temperature()
37
>>> c.set_temperature(10)
>>> c.set_temperature(-300)
Traceback (most recent call last):
...
ValueError: Temperature below -273 is not possible

This update carries the new restriction. They can no longer set the temperature below -273.
Note that there is a private variable in Python. Only rules can be followed. Languages do not apply any type of restrictions.

>>> c._temperature = -300
>>> c.get_temperature()
-300

But this does not matter a big concern. A big problem with the previous update, all clients that previously held classes in the program that have to change their code from obj.temperature to obj.get_temperature () and all assignments like obj.temperature to obj.set_temperature = Val (Val ).
This refactoring can cause customers headaches with hundreds of thousands of code lines.
All in all, the new update that did not stop adjustment. These treasures came to save.


The Power of @property:


Pythonic way to deal with the above problems is the use of pra property. This is what we could have achieved.

class Celsius:
    def __init__(self, temperature = 0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32

    def get_temperature(self):
        print("Getting value")
        return self._temperature

    def set_temperature(self, value):
        if value < -273:
            raise ValueError("Temperature below -273 is not possible")
        print("Setting value")
        self._temperature = value
 temperature = property(get_temperature,set_temperature)

We have added a print function () inside get_temperature () and set_temperature () to clearly observe that they are being executed.

>>> c = Celsius()

The last line of code akes the air properties of the object. In short, a friction property code (get_temperature and set_temperature) in the access element (air).
What is the code that retrieves the air value will automatically call get_temperature () instead of a dictionary (__dict__) look-up? ?n the same way, all the code that determines the value of the temperature will automatically call set_temperature (). This is one of the interesting features in Python.
We can see that the upper set_temperature () known though we made an object.

Can you guess why?


The reason is that when an object is created, the __init __ () method is called. That's the line self.temperature = air. Do this automatically called set_temperature ().

>>> c.temperature
Getting value
0

By using the property, we can see that we have modified our class and stopped without changes to the restriction value needed for the client code. So, the implementation of our back to the whole compatible world and is happy.

>>> c.temperature = 37
Setting value
>>> c.to_fahrenheit()
Getting value
98.60000000000001

Finally, keep in mind that, the real value of the temperature is stored in the variable _Temperature private. The temperature of the attributes of the objects are properties that provide an interface for the private variable.

Digging Deeper into Property:


In Python, the properties () is an embedded function that creates and returns an object property. Signature of this function

property(fget=None, fset=None, fdel=None, doc=None)

Programmers familiar with decorators in Python can recognize that the previous construction can be implemented as decorators.

>>> property()
<property object at 0x0000000003239B38>

You can not then go on to determine the name of the set_temperature get_temperature since they need to contaminate the namespace and class. To do this, we use the name of our terms temperature while functions get and set. This is the way it can be done.

class Celsius:
    def __init__(self, temperature = 0):
        self._temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32

    @property
    def temperature(self):
        print("Getting value")
        return self._temperature

    @temperature.setter
    def temperature(self, value):
        if value < -273:
            raise ValueError("Temperature below -273 is not possible")
        print("Setting value")
        self._temperature = value


Putting the above into practice is two simple and recommended ways to make properties.


To getting expect level training for Python training in your Location – Python training in Chennai | Python training institute in Chennai | Python Course institute in Chennai | Python training in Bangalore | Python training institute in Bangalore Python training in Electronic City Python training in Jaya Nagar | Python training in Pune | Python training institute in Pune | Python training in OMR | Python training in Velachery | Python training in Tambaram Python training in Annanagar | Python training in Marathahalli Python training in Btm | Python Online Training | Online Certification Course Python Course in Chennai Python interview questions and answers | Python tutorials | Python training in Indira Nagar | Python Course in Btm | Python Course in Marathahalli Python training institute in Marathahalli Python course institute in Btm Python course in Electronic City | Python online training in Chennai | Python online training in Bangalore

Comments

Post a Comment

Popular posts from this blog

Python – Functions

What is Django in python?