Print in getter of a property not working?
<p>I am new to python, currently trying to learn properties. </p>

<pre><code>class Car(object):
    def set_speed(self, speed):
        self._speed = speed
        print("set speed to {}".format(self.speed))


    def get_speed(self):
        return self._speed
        print("the speed is {}".format(self.speed))


    speed = property(fget = get_speed, fset=set_speed)

car1 = Car()
car1.speed = 170
x = car1.speed
</code></pre>

<p>The output I get is <code>set speed to 170</code> </p>

<p>That is all well and fine, and there is no surprise here since <code>car1.speed</code> was called. However, why was there never a <code>"The speed is 170"</code> printline?
<code>car1.speed</code> was called in the same manner? Is there something I have not understood?</p>

<p>You used a <code>return</code> statement <em>before</em> the <code>print()</code> call. The function execution <em>ends</em> at that point, the <code>print()</code> is never reached:</p>

<pre><code>def get_speed(self):
    # return ends a function
    return self._speed
    # anything beyond this point is ignored
    print("the speed is {}".format(self.speed))
</code></pre>

<p>Put the <code>print()</code> call <em>before</em> the return statement:</p>

<pre><code>def get_speed(self):
    print("the speed is {}".format(self._speed))
    return self._speed
</code></pre>

<p>I corrected the <code>print()</code> function to show <code>self._speed</code> (<em>with</em> an underscore in the attribute name), otherwise you'd get into an infinite recursion (since <code>self.speed</code> would trigger the property again getter). You probably want to do the same in the <code>set_speed()</code> function, as that'll trigger the <code>get_speed()</code> getter too and you'll see <code>the speed is &lt;newspeed&gt;</code> printed before <code>set speed to &lt;newspeed&gt;</code> is printed each time you change the speed:</p>

<pre><code>class Car(object):
    def set_speed(self, speed):
        self._speed = speed
        print("set speed to {}".format(speed))

    def get_speed(self):
        print("the speed is {}".format(self._speed))
        return self._speed

    speed = property(fget = get_speed, fset=set_speed)
</code></pre>

<p>Next, you can use the <code>property</code> object as a <em>decorator</em>; the resulting <code>property</code> instance has a <code>setter()</code> method that can then be re-used to decorate the setter too:</p>

<pre><code>class Car(object):
    @property
    def speed(self):
        print("the speed is {}".format(self._speed))
        return self._speed

    @speed.setter
    def speed(self, speed):
        self._speed = speed
        print("set speed to {}".format(speed))
</code></pre>

<p>See <a href="https://stackoverflow.com/questions/17330160/how-does-the-property-decorator-work">How does the @property decorator work?</a> as to how that works.</p>

python properties