Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Ankit Bindal
Ankit Bindal
2,830 Points

What is @property in python classes ?

I just came across an example where something like:

@property
def foo(x):
    # something

was used. Does anyone knows what is this and when to implement this ? Thanks in advance !

1 Answer

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

property is a decorator that makes a method behave like an attribute.

On a class instance, attributes are extra bits of information you can access with dot notation and no parentheses.

class Student:
     name = "Ankit"

a = Student()
print(a.name)
Ankit

A property is accessed the same way but they're constructed differently.

class Student:
    first_name = "Ankit"
    last_name = "Bindal"

    @property
    def full_name(self):
        return "{} {}".format(self.first_name, self.last_name)

a = Student()
print(a.full_name)
Ankit Bindal