@property

TL;DR

  • Getters and setters are used to add validation for getting and setting values or to avoid direct access of a class field.
  • We can use property, and call it as an instance variable. So, by this we are telling that the property is too cheap to compute, and no need to make it a function.
  • Or we can use property, to create another attributes based on that. Ex: Celsius, Fahrenheit.
  • If attribute value not passed in initializer, then use _.

Using property decorator

  1. When inheriting property, you should do as usual and redefine getters, setters, and deleter
  2. If only either getter or setter use @ParentClass.attribute.setter
  3. class SubPerson(Person): 
    	@Person.name.getter 
    	def name(self):
    		print('Getting name') 
    		return super().name
    
    class SubPerson(Person): 
      @Person.name.setter 
      def name(self, value):
    	  print('Setting name to', value)
    	  super(SubPerson, SubPerson).name.__set__(self, value)

Read-write and read-only

# Readwrite as usual
class Point:
    def __init__(self, x):
        self.x = x

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        try:
            self._x = float(value)
            print("Validated!")
        except ValueError:
            raise ValueError('"x" must be a number') from None

Property as function

The setter method converts the input value for the ATTRIBUTE (radius) and assigns it to the non-public ._radius, which is the variable you use to store the final data.

@property is just the syntactic sugar

Example

References

SuperMade with Super