Property in Child Class
Posted on Tue, 30 May 2017 in Python
It looks obvious that you can override the property in a child class, and call "super" within it. Sounds OK? Yes, it is. However, when my colleague asked me about this behavior, I was confused. Maybe because I am a bit suspicious, every time I saw a magic thing of any kind in a code I expect a trap. What's why I decided to write a simple example to prove myself that it works as it should.
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, absolute_import
class Parent(object):
@property
def prop(self):
print("Parent property")
class Child(Parent):
@property
def prop(self):
super(Child, self).prop
print("Child property")
child = Child()
child. prop
Works as expected.
Parent property
Child property
Actually, property decorator just set up an object of a special type instead of function (it's also an object of another special type) and don't touch any internal things in class. So this behavior is expected and clearly described in the documentation. But, who reads docs?
---
Got a question? Hit me on Twitter: avkorablev
Got a question? Hit me on Twitter: avkorablev