Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing super() in a property's setter method when using the @property decorator raises an AttributeError
    primarykey
    data
    text
    <p>I am a little confused by the behavior when attempting to overwrite a property in a subclass. </p> <p>The first example sets up two classes, <code>Parent</code> and <code>Child</code>. <code>Parent</code> inherits from <code>object</code>, while <code>Child</code> inherits from <code>Parent</code>. The property <code>a</code> is defined using the property decorator. When <code>child.a</code>'s setter method is called, an <code>AttributeError</code> is raised. </p> <p>In the second example, by using the <code>property()</code> function rather than the decorator, everything works as would be expected.</p> <p>Can anyone shed some light on why the behavior differs? Also, yes, I know that the <code>__init__</code> definition in Child is not needed.</p> <h3>Example 1 - Using <code>@property</code></h3> <pre><code>class Parent(object): def __init__(self): self._a = 'a' @property def a(self): return self._a @a.setter def a(self, val): self._a = val class Child(Parent): def __init__(self): super(Child, self).__init__() @property def a(self): return super(Child, self).a @a.setter def a(self, val): val += 'Child' super(Child, self).a = val p = Parent() c = Child() print p.a, c.a p.a = 'b' c.a = 'b' print p.a, c.a </code></pre> <h3>Example 1 return - Raises an attribute error</h3> <pre><code>a a Traceback (most recent call last): File "testsuper.py", line 26, in &lt;module&gt; c.a = 'b' File "testsuper.py", line 20, in a super(Child, self).a = val AttributeError: 'super' object has no attribute 'a' </code></pre> <h3>Example 2 - <code>Using property()</code></h3> <pre><code>class Parent(object): def __init__(self): self._a = 'a' def _get_a(self): return self._a def _set_a(self, val): self._a = val a = property(_get_a, _set_a) class Child(Parent): def __init__(self): super(Child, self).__init__() def _get_a(self): return super(Child, self)._get_a() def _set_a(self, val): val = val+'Child' super(Child, self)._set_a(val) a = property(_get_a, _set_a) p = Parent() c = Child() print p.a, c.a p.a = 'b' c.a = 'b' print p.a, c.a </code></pre> <h3>Example 2 return - Works correctly</h3> <pre><code>a a b bChild </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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