Note that there are some explanatory texts on larger screens.

plurals
  1. POOverriding properties in python
    text
    copied!<p>So, I'm trying to figure out the best (most elegant with the least amount of code) way to allow overriding specific functions of a property (e.g., just the getter, just the setter, etc.) in python. I'm a fan of the following way of doing properties, due to the fact that all of their methods are encapsulated in the same indented block of code (it's easier to see where the functions dealing with one property stop and the functions dealing with the next begin):</p> <pre><code>@apply def foo(): """A foobar""" def fget(self): return self._foo def fset(self, val): self._foo = val return property(**locals()) </code></pre> <p>However, if I want to inherit from a class that defines properties in this manner, and then, say, override the <code>foo</code> setter function, it seems tricky. I've done some searching and most of the answers I've found have been to define separate functions in the base class (e.g. <code>getFoo</code> and <code>setFoo</code>), explicitly create a property definition from them (e.g. <code>foo = property(lambda x: x.getFoo(), lambda x, y: x.setFoo(y), lambda x: x.delFoo())</code>), and then override <code>getFoo</code>, <code>setFoo</code>, and <code>delFoo</code> as needed.</p> <p>I dislike this solution because it means I have to define lambas for every single property, and then write out each function call (when before I could have just done <code>property(**locals())</code>). I also don't get the encapsulation that I had originally.</p> <p>Ideally, what I would like to be able to do would be something like this:</p> <pre><code>class A(object): def __init__(self): self.foo = 8 @apply def foo(): """A foobar""" def fget(self): return self._foo def fset(self, val): self._foo = val return property(**locals()) class ATimesTwo(A): @some_decorator def foo(): def fset(self, val): self._foo = val * 2 return something </code></pre> <p>And then the output would look something like:</p> <pre><code>&gt;&gt;&gt; a = A() &gt;&gt;&gt; a.foo 8 &gt;&gt;&gt; b = ATimesTwo() &gt;&gt;&gt; b.foo 16 </code></pre> <p>Basically, <code>ATimesTwo</code> inherits the getter function from <code>A</code> but overrides the setter function. Does anybody know of a way to do this (in a manner that looks similar to the example above)? What function would the <code>some_decorator</code> look like, and what should the <code>foo</code> function return?</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