Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python properties and inheritance

I have a base class with a property which (the get method) I want to overwrite in the subclass. My first thought was something like:

class Foo(object):     def _get_age(self):         return 11      age = property(_get_age)   class Bar(Foo):     def _get_age(self):         return 44 

This does not work (subclass bar.age returns 11). I found a solution with an lambda expression which works:

age = property(lambda self: self._get_age()) 

So is this the right solution for using properties and overwrite them in a subclass, or are there other preferred ways to do this?

like image 900
Peter Hoffmann Avatar asked Oct 26 '08 02:10

Peter Hoffmann


People also ask

Are properties inherited Python?

Inheritance allows us to define a class that inherits all the methods and properties from another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class.

What is the inheritance in Python?

Inheritance in Python Inheritance is a powerful feature in object oriented programming. It refers to defining a new class with little or no modification to an existing class. The new class is called derived (or child) class and the one from which it inherits is called the base (or parent) class.

What is inheritance in python and its types?

Inheritance is a process of obtaining properties and characteristics(variables and methods) of another class. In this hierarchical order, the class which inherits another class is called subclass or child class, and the other class is the parent class.

What are properties in class in Python?

Python's property() is the Pythonic way to avoid formal getter and setter methods in your code. This function allows you to turn class attributes into properties or managed attributes. Since property() is a built-in function, you can use it without importing anything.


1 Answers

I simply prefer to repeat the property() as well as you will repeat the @classmethod decorator when overriding a class method.

While this seems very verbose, at least for Python standards, you may notice:

1) for read only properties, property can be used as a decorator:

class Foo(object):     @property     def age(self):         return 11  class Bar(Foo):     @property     def age(self):         return 44 

2) in Python 2.6, properties grew a pair of methods setter and deleter which can be used to apply to general properties the shortcut already available for read-only ones:

class C(object):     @property     def x(self):         return self._x      @x.setter     def x(self, value):         self._x = value 
like image 106
piro Avatar answered Sep 19 '22 23:09

piro