Python super and setting parent class property

I have a very strange problem with Python super () and inheritance and properties. First, the code:

#!/usr/bin/env python3 import pyglet import pygame class Sprite(pyglet.sprite.Sprite): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.rect = pygame.Rect(0, 0, self.width, self.height) self.rect.center = self.x, self.y @property def x(self): return super().x @x.setter def x(self, value): super(Sprite, self.__class__).x.fset(self, value) self.rect.centerx = value @property def y(self): return super().y @y.setter def y(self, value): super(Sprite, self.__class__).y.fset(self, value) self.rect.centery = value 

It works great. However, what I want (which seems to me Pythonic)

 #super(Sprite, self.__class__).x.fset(self, value) super().x = value 

doesn't work though

 super().x 

gets a fine value. x in this case is a property of the superclass with both fset and fget defined. So why doesn't it work?

+17
python super
May 30 '12 at 5:19
source share
1 answer

I tried to find the right language to support why this behavior is the way it is, so as not to give you “because it is just” the answer ... But it seems that this question has been asked more than once and that it comes down to super() behavior super() . You can see the 2010 discussion about this exact behavior here: http://mail.python.org/pipermail/python-dev/2010-April/099672.html

Ultimately, it really comes down to super () calls, which allow you to directly access getters, not setters. fset() can be accessed via fset() or __set__() . This is probably easiest to explain because the super () function simply does not support it. "It will allow the functionality of the“ get ”operation, not the setter in the left-hand assignment, in the“ given ”operation (therefore, calling the fset() method) As you can see from the date of this discussion, it is obvious that this has happened since the introduction of super() .

Maybe someone has a more specific technical reason, but to be honest, I'm not sure if that even matters. If you don’t support it, this is a pretty good reason.

+15
May 30 '12 at 5:38
source share



All Articles