add methods in subclasses within the super class constructor
Posted
by deamon
on Stack Overflow
See other posts from Stack Overflow
or by deamon
Published on 2010-04-28T08:15:49Z
Indexed on
2010/04/28
8:23 UTC
Read the original article
Hit count: 465
I want to add methods (more specifically: method aliases) automatically to Python subclasses. If the subclass defines a method named 'get' I want to add a method alias 'GET' to the dictionary of the subclass.
To not repeat myself I'd like to define this modifation routine in the base class. But if I check in the base class init method, there is no such method, since it is defined in the subclass. It will become more clear with some source code:
class Base:
def __init__(self):
if hasattr(self, "get"):
setattr(self, "GET", self.get)
class Sub(Base):
def get():
pass
print(dir(Sub))
Output:
['__doc__', '__init__', '__module__', 'get']
It should also contain 'GET'
.
Is there a way to do it within the base class?
© Stack Overflow or respective owner