'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.
Solution 1:[1]
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
Solution 2:[2]
You could override the class method with another class method that takes an instance of that class as an argument. In that method, do what you need to do to it and then return it. That way you could do
instance = Child.do_something(instance)
However, I do not recommend doing that whatsoever.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rik Poggi |
Solution 2 | Tyler Crompton |