Python定义方法之外的类定义? [英] Python define method outside of class definition?

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

问题描述

class MyClass:
    def myFunc(self):
        pass

我可以创建类定义的MyFunc outisde吗?也许在另一个模块中?

Can I create MyFunc outisde 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(object):
    myMethod = func

您还可以在定义后添加一个函数:

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

class MyClass(object):
    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.

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

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