Skip to content

Instantly share code, notes, and snippets.

@AstraLuma
Last active May 27, 2017 09:26
Show Gist options
  • Save AstraLuma/c1a3cdd46457cae5602b03f6ce1e4572 to your computer and use it in GitHub Desktop.
Save AstraLuma/c1a3cdd46457cae5602b03f6ce1e4572 to your computer and use it in GitHub Desktop.
class Top:
@property
def foo(self):
...
@foo.setter
def set_foo(self, value):
...
class Spam(Top):
@property
def foo(self)
return super().foo
@foo.setter
def foo(self, value):
super().foo = value
...
class Top:
def get_foo(self):
...
def set_foo(self, value):
...
foo = property(get_foo, set_foo)
class Spam(Top):
# Probably the simplest, but ignores MRO
def set_foo(self, value):
super().set_foo(value)
...
foo = property(Top.get_foo, set_foo)
class Eggs(Top):
# More complicated, but respects MRO
def set_foo(self, value):
super().set_foo(value)
...
foo = property(
(lambda self: self.get_foo()),
(lambda self, value: self.set_foo(value)
)
class Sausage(Top):
# This just won't work
def set_foo(self, value):
super().set_foo(value)
...
@PiDelport
Copy link

PiDelport commented May 27, 2017

In override-decorators.py, this code doesn't make sense:

  @foo.setter
  def set_foo(self, value):
    ...

The setter definition should be named foo, too, or the setting property won't be available as foo. (In other words, foo will remain a read-only property, while set_foo will become a new property that both gets (with foo's getter) and sets.)

@PiDelport
Copy link

PiDelport commented May 27, 2017

Here's a working example of property extension:

class Top:

    @property
    def foo(self):
        …

    @foo.setter
    def foo(self, value):
        …


class Spam(Top):

    @property
    def foo(self):
        return super().foo

    @foo.setter
    def foo(self, value):
        # This is the tricky bit: super() seems to only implement getting, not setting. (?)
        # So, we have to simulate super().foo = value
        super(Spam, type(self)).foo.fset(self, value)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment