2 weeks, 5 days

Python property() Function




Python’s property() is the Pythonic way to avoid formal getter and setter methods in your code. This function allows you to turn class attributes into properties or managed attributes. Since property() is a built-in function, you can use it without importing anything. Additionally, property() was implemented in C to ensure optimal performance.

Python property() function returns the object of the property class and it is used to create the property of a class. 

Syntax: property(fget, fset, fdel, doc)                        

Parameters:                                                 

  • fget() – used to get the value of attribute                       
  • fset() – used to set the value of attribute                                  
  • fdel() – used to delete the attribute value                                
  • doc() – string that contains the documentation (docstring) for the attribute                   

Return: Returns a property attribute from the given getter, setter and deleter.

Note:                                                                                                       

  • If no arguments are given, property() method returns a base property attribute that doesn’t contain any getter, setter, or deleter.
  • If doc isn’t provided, property() method takes the docstring of the getter function.

class Animal:
    def __init__(self,name,age):
        self._name = name
        self._age = age  
    def get_age(self):
        return self._age   
    def set_age(self,age):
        self._age = age

    def get_name(self):
        return self._name   
    def set_name(self,name):
        self._name = name
    pet = property(fget = get_name,fset = set_name)
    age = property(fget = get_age,fset = set_age)
ct = Animal("cat",17)          
print(ct.pet)                       
print(ct.age)                     

class Area:                
    def __init__(self, radius):
        self._radius = radius
    def get_area(self):
        pi = 3.14                 
        return pi * self._radius ** 2
    def set_radius(self,r):
        self._radius = r
    area = property(fget = get_area, fset = set_radius)    
num = Area(7)             
print(num.area)           

class Volume:               
    def __init__(self,x, y, z):
        self.set_value(x,y,z)
    def set_value(self,a,b,c):
        self.x = a               
        self.y = b               
        self.z = c              
    def get_volume(self):
        return self.x * self.y * self.z
    game = property(fget= get_volume, fset = set_value)
vol = Volume(3,5,7)  
print(vol.game)         
class Cylinder:
    def __init__(self,h, r):
        self._h = h
        self._r = r
    def set_value(self, h, r):
        self._h = h
        self._r = r
    def get_volume(self):
        pi =  3.14
        return pi*self._h * self._r * self._r
    vol = property(fget= get_volume, fset = set_value)
c = Cylinder(7,17)         
print(c.vol)                    

Python @property Using Decorator                                    

In Python, everything is an object. Functions in Python are first-class objects which means that they can be referenced by a variable, added to the lists, passed as arguments to another function, etc.

A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. In other words, the decorators are used to modify the behavior of function or class. In Decorators, functions are taken as the argument into another function and then called inside the wrapper function.

Getters and setters are used in many object-oriented programming languages to ensure the principle of data encapsulation. These methods are, of course, the getter for retrieving the data and the setter for changing the data. According to this principle, the attributes of a class are made private to hide and protect them from other codes. @property is basically a pythonic way to use getters and setters.

 

The syntax used to define properties is very concise and readable. You can access instance attributes exactly as if they were public attributes while using the "magic" of intermediaries (getters and setters) to validate new values and avoid accessing or modifying the data directly. By using @property, you can "reuse" the name of a property to avoid creating new names for the getters, setters, and deleters.


class Car:                                    
    def __init__(self,brand, model):
        self._brand = brand              
        self._model = model            
    @property                              
    def brand(self):                    
        return self._brand            
    @brand.setter                    
    def brand(self, name):        
        self._brand = name       
    @brand.deleter               
    def brand(self):               
        del self._brand           
    @property                    
    def model(self):            
        return self._model       
    @model.setter                 
    def model(self, year):        
        if isinstance(year, int):
            self._model = year
        else:                                     
            raise TypeError("Invalid")
    @model.deleter                   
    def model(self):                     
        del self._model                   
car = Car("Audi",2023)               
print(car.__dict__)                      
del car.brand                               
del car.model                               
print(car.__dict__)                       
class Area:                         
    def __init__(self, radius):
        self.radius =radius
        self.area = None
    @property                    
    def get_radius(self):
        return self.radius
    @get_radius.setter
    def set_radius(self, r):
        self.radius = r       
        self.area = None
    @property                  
    def get_area(self):
        pi = 3.14                      
        if self.area is None:
            self.area = pi * self.radius * self.radius             
        return self.area         
circle = Area(17)             
class Number:                      
    def __init__(self,x = 0):
        self.y = x                         
    @property                   
    def get_val(self):                  
        return self.y                 
    @get_val.setter                      
    def set_val(self, z):                 
        if isinstance(z, int) and 0 < z and z < 542:
            self.y = z
        else:                          
            raise TypeError("Invalid")
arr = [Number(17), Number(7), Number(), Number(123)]            
print([i.y for i in arr])          

 
class Pet:
    def __init__(self, name, age):
        self._name = name
        self._age = age        
    @property            
    def get_name(self):
        return self._name 
    @get_name.setter
    def set_name(self, name):
        if isinstance(name, str):
            self._name = name
        else:              
            raise TypeError("Invalid")
    @property               
    def get_age(self):
        return self._age 
    @get_age.setter
    def set_age(self, age):
        if isinstance(age, int):
            self._age = age
        else:               
            raise TypeError("Invalid age")
cat = Pet("Cat",7)             
print(cat.__dict__)             

 


Responses(0)







Related