Python @property decorator

The @property is used to define new properties or modify existing ones. For example:

class CodesCracker:
    def __init__(self, val):
        self.v = val

    @property
    def val(self):
        print("\nGetting the Value")
        return self.v

    @val.setter
    def val(self, val):
        print("\nNow Setting the Value to \"", val, "\"", sep="")
        self.v = val

    @val.deleter
    def val(self):
        print("\nDeleting the Value")
        del self.v

a = CodesCracker("Python is Fun!")
print(a.val)

a.val = "Python is an Object-oriented PL"
print(a.val)

del a.val

The sample output of the above program, demonstrating the @property decorator in Python, is shown in the snapshot given below:

python property decorator

The way to use the @property decorator, either to define new properties or to modify the existing ones, is:

class C(object):
    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

For example:

class CodesCracker:
    def __init__(self, stud):
        self.s = stud

    @property
    def stud(self):
        print("\nGetting the Name of Student...")
        return self.s

    @stud.setter
    def stud(self, nstud):
        print("\nNow Setting Name of Student to \"", nstud, "\"", sep="")
        self.s = nstud

    @stud.deleter
    def stud(self):
        print("\nDeleting the Name of Student...")
        del self.s


x = CodesCracker("Emily Cale")
print("The Name of Student is:", x.stud)
x.stud = "Joey Lynn King"
print("Now the Name of Student is:", x.stud)
del x.stud

The snapshot given below shows, of course, the sample output of this program:

python property decorator example

Advantages of the @property decorator in Python

Disadvantages of the @property decorator in Python

Python Online Test


« Previous Tutorial Python Keywords »


Liked this post? Share it!