Consider the following code:
class BaseClass(object):
def _del_property(attr):
"""Abstract deller"""
def del_attr(self):
setattr(self, attr, None)
return del_attr
def _set_property(attr):
"""Abstract setter."""
def set_attr(self, x):
setattr(self, attr, x)
return set_attr
def _get_property(attr):
"""Abstract getter"""
def get_attr(self):
getattr(self, attr)
return get_attr
_name = None
name = property(fget=_get_property('_name'), fset=_set_property('_name'))
class Component(BaseClass):
_material = None
material = property(fget=_get_property('_material'), fset=_set_property('_material'), fdel=_del_property('_material'))
How come _get_property, _set_property and _del_property are not inherited?
How can it be achieved?
It should work for derived classes in the same source file, as well as for derived classes in a separate file, which import this source file with a
from filename import *
When creating a class, a new namespace is created. Python reads the block of code inside your class block and then passes the information to
type(or the corresponding metaclass). In this case, python complains because when setting up theComponentclass,_get_propertyisn’t defined within that scope — perhapsBaseClass._get_property, but that probably won’t work like you want it to either.One easy fix is to make those functions module level functions since the class namespace has access to the module namespace:
Perhaps it’s more instructive to look at the class while we’re creating it:
This will print:
So, you’re dealing with a regular function inside
BaseClass, but it becomes aninstancemethodaftertypedoes it’s magic.Personally, I would just create a convenience function:
Which you can then use. If you really want to, you could even put it on
BaseClassas astaticmethod:Then your derived classes would look like: