Python @property Decorator

The @property is used to define new properties or to modify the 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 above program, demonstrating the @property decorator in Python, is shown in the snapshot given below:

python property decorator

The way to use @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, of course show the sample output of this program:

python property decorator example

Python Online Test


« Previous Tutorial Next Tutorial »

Follow/Like Us on Facebook




Subscribe Us on YouTube