Defining a method outside of a Python class

I’m having some fun reading the source code for Whisper: https://github.com/openai/whisper.

One thing I learned from it that delighted (horrified?) me: you can use a function defined outside of a class to provide the implementation for a method. (E.g., used in their Whisper class.)

def foo(self, x):
  return self.bar(x) + 1

class F:
  def bar(self, x):
    return 10 * x
  fff = foo

> f = F()
> f.fff(11)
111

That’s fun. I don’t have a use case in mind yet myself, but it’s good to know.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *