在类定义之外定义方法? [英] Define a method outside of class definition?

查看:75
本文介绍了在类定义之外定义方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class MyClass:
    def myFunc(self):
        pass

我是否可以在类定义之外创建MyFunc(),甚至可以在另一个模块中创建?

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

推荐答案

是.您可以在类外部定义函数,然后在类主体中将其用作方法:

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.

我要指出的是,尽管这在Python中是可能的,但这有点不寻常.您在评论中提到允许用户添加更多"方法.听起来很奇怪.如果要编写库,则可能不希望该库的用户向库中的类动态添加方法.库用户创建自己的从您的类继承的子类比直接更改您的子类更为正常.

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.

这篇关于在类定义之外定义方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆