Python property() Method

The property() method returns the property attribute.

propert() Syntax:

property(fget, fset, fdel, doc)

Parameters:

  1. fget: (Optional) Function for getting the attribute value. Default value is none.
  2. fset: (Optional) Function for setting the attribute value. Default value is none.
  3. fdel: (Optional) Function for deleting the attribute value. Default value is none.
  4. doc: (Optional) A string that contains the documentation. Default value is none.

Return Value:

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

It is recommended to use the property decorator instead of the property() method.

The following example demonstrates the property() method.

Example: property()
class Student:
    def __init__(self, name,age):
        self.fname = name
        self.age = age

    def get_name(self):
        print('Getting name of student.')
        return self.fname

    def set_name(self, value):
        print('Setting name of the student to ' + value)
        self.fname = value

    def del_name(self):
        print('Deleting name of the student')
        del self.fname

    # Set property to use get_name, set_name
    # and del_name methods
    name = property(get_name, set_name, del_name, 'Student property')

p = Student('John',20)
print(p.name)
p.name = 'Doe'
del p.name
Output
Getting name of student.
John
Setting name of the student to Doe
Deleting name of the student
Want to check how much you know Python?