An Introduction Python @property – Python Tutorial

By | February 3, 2022

We may find @property in the front of some python functions. For example:

An Introduction Python @property – Python Tutorial

In this tutorial, we will introduce you how to use @property in python.

Python @property decorator

@property decorator is usually used in the front of some python class functions. It can make these functions can be used as class property.

For example:

class Rect:
    def __init__(self, w, h):
        self.w = w
        self.h = h
        
    @property
    def width(self):
        return self.w
    @property
    def height(self):
        return self.h

In this example, width() and height() functions are decorated by @property. We can use them as a variable.

For example:

r = Rect(10, 5)

print(r.width, r.height)

Run this code, we will get:

10 5

How about @property function does not return anything?

Look at this example:

    @property
    def width(self):
        self.w = 100

Run this code, we will get:

None 5

It means @property function will return None defaultly.

How about calling @property function as a normal function?

For example:

print(r.height())

Run this code, we will find this error: TypeError: ‘int’ object is not callable

It means we can not use a @property function like a normal function.

Leave a Reply