Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How and when are python @properties evaluated

Here's a snippet of code.

class TestClass:
    def __init__(self):
        self.a = "a"
        print("calling init")

    @property
    def b(self):
        b = "b"
        print("in property")
        return b

test_obj = TestClass()
print("a = {} b = {}".format(test_obj.a,test_obj.b))

I'm trying to understand when the variable b defined inside test_obj gets its value of "b".

As you can see from the below screenshot, the statement on line 13 is yet to be evaluated/executed but already the value of b for test_obj has been initialized. Debugging this by placing a breakpoint on literally every single line didn't help me understand how this is happening.

enter image description here Can someone please explain this to me ?

like image 653
Dhiwakar Ravikumar Avatar asked Sep 13 '18 11:09

Dhiwakar Ravikumar


People also ask

How does @property work Python?

The property() method in Python provides an interface to instance attributes. It encapsulates instance attributes and provides a property, same as Java and C#. The property() method takes the get, set and delete methods as arguments and returns an object of the property class.

Why @property is used in Python?

The @property is a built-in decorator for the property() function in Python. It is used to give "special" functionality to certain methods to make them act as getters, setters, or deleters when we define properties in a class.

How is a property created in Python?

Python property() function returns the object of the property class and it is used to create property of a class. Parameters: fget() – used to get the value of attribute. fset() – used to set the value of attribute.

What does property decorator do in Python?

@property decorator is a built-in decorator in Python which is helpful in defining the properties effortlessly without manually calling the inbuilt function property(). Which is used to return the property attributes of a class from the stated getter, setter and deleter as parameters.


1 Answers

More likely, the IDE is trying to show you what the value of test_obj.b is. For that it gets the value from test_obj.b. Since it doesn't make much of a difference whether b is an attribute or a @property, the debugger essentially just does test_obj.b for you, which gives it the value 'b'.

The function def b works exactly as you might expect from any other ordinary function; it's just that the debugger/IDE implicitly invokes it for you.

like image 134
deceze Avatar answered Oct 21 '22 08:10

deceze