Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python overriding a classmethod with an instance method

I came across a bug in my code where an overriding method was hidden because I'd forgotten the @classmethod decorator. I was wandering if it's possible to force the other way (noted it's probably bad design) but something like:

 class Super:

   @classmethod
   def do_something(cls):
     ...

class Child:
  def do_something(self):
    ...

obj = Child()
obj.do_something() #calls the child
Child.do_something() #calls the Super method

EDIT: No specific case at the moment but I was wandering if it could hypothetically be done.

like image 723
probably at the beach Avatar asked Feb 14 '12 17:02

probably at the beach


1 Answers

As a pure hypothetically application, this could be one way:

class Super:
   @classmethod
   def do_something(cls):
     print('Super doing something')

class Child(Super):
    def __init__(self):
        self.do_something = lambda: print('Child Doing Something')

Example:

>>> obj = Child()
>>> obj.do_something()
Child Doing Something
>>> Child.do_something()
Super doing something
>>> obj.do_something()
Child Doing Something
like image 71
Rik Poggi Avatar answered Oct 02 '22 00:10

Rik Poggi