Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Python does indeed not feature method overloading, but you're correct that the docs encourage you to name the getters and setters identically, and demonstrates it to boot. What's going on here?</p> <p>The trick is to understand how method decorators work in Python. Whenever you see something like this:</p> <pre><code>@foo def bar(): frob() quux() </code></pre> <p>what Python actually does under the covers is to rewrite it this way:</p> <pre><code>def bar(): frob() quux() bar = foo(bar) </code></pre> <p>In other words: define a function <code>bar</code>, then replace it with the result of calling <code>foo</code> <em>on the bar function</em>.</p> <p>While that's all true, the order of evaluation is actually slightly different than the above when it comes to how names are resolved. It might be easier for you to pretend for a moment that what actually happens looks a bit closer to this:</p> <pre><code>def __secret_internal_function_name__(): frob() quux() bar = foo(__secret_internal_function_name__) </code></pre> <p>Why does this matter? Let's look at the Python in that documentation link:</p> <pre><code>class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x </code></pre> <p>Let's rewrite this using what we now know to understand what Python is actually doing:</p> <pre><code>class C(object): def __init__(self): self._x = None def __secret_x_prop__(self): """I'm the 'x' property.""" return self._x x = property(__secret_x_prop__) def __secret_x_setter__(self, value): self._x = value x = x.setter(__secret_x_setter__) def __secret_x_getter__(self): del self._x x = x.deleter(__secret_x_getter__) </code></pre> <p>Now, we can actually see what's going on: we're not overloading functions; we're gradually building up a <code>property</code> object that references other functions.</p> <p>It's also worth noting that, depending on how you create the property, the names don't need to match. Specifically, if you create the property explicitly with the <code>property</code> function, as is done in the first example in the documentation, the names can be whatever you want; the example has them called <code>getx</code>, <code>setx</code>, and <code>delx</code>, and it works fine. In what I assume is a safety precaution, <code>property.setter</code>, <code>property.deleter</code>, and the like <em>do</em> require the function passed have the same name, but they're doing the same thing behind the scenes as the more explicit <code>property</code> example.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload