Python overriding class method with instance method

I ran into an error in my code where the hidden method was hidden because I forgot the @classmethod decorator. I wandered if it was possible to force a different path (it was probably marked by a 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 wandered if it could be hypothetically done.

+4
source share
2 answers

As a purely hypothetical 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 
+3
source

You can override a class method with another class method that takes an instance of this class as an argument. In this method, do what you need to do, and then return it. So you could do

 instance = Child.do_something(instance) 

However, I do not recommend doing this.

+1
source

Source: https://habr.com/ru/post/1396448/


All Articles