Define a method outside of class definition?

前端 未结 4 445
天命终不由人
天命终不由人 2020-11-30 00:01
class MyClass:
    def myFunc(self):
        pass

Can I create MyFunc() outside of the class definition, maybe even in another module?

4条回答
  •  眼角桃花
    2020-11-30 00:25

    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.

提交回复
热议问题