Define a method outside of class definition?

Yes. You can define a function outside of a class and then use it in the class body as a method:

def func(self):
    print("func")

class MyClass:
    myMethod = func

You can also add a function to a class after it has been defined:

class MyClass:
    pass

def func(self):
    print("func")

MyClass.myMethod = func

You can define the function and the class in different modules if you want, but I’d advise against defining the class in one module then importing it in another and adding methods to it dynamically (as in my second example), because then you’d have surprisingly different behaviour from the class depending on whether or not another module has been imported.

I would point out that while this is possible in Python, it’s a bit unusual. You mention in a comment that “users are allowed to add more” methods. That sounds odd. If you’re writing a library you probably don’t want users of the library to add methods dynamically to classes in the library. It’s more normal for users of a library to create their own subclass that inherits from your class than to change yours directly.

I’d also add a reminder that functions don’t have to be in classes at all. Python isn’t like Java or C# and you can just have functions that aren’t part of any class. If you want to group together functions you can just put them together in the same module, and you can nest modules inside packages. Only use classes when you need to create a new data type, not just to group functions together.

Leave a Comment