为什么总是将 self 添加为类方法的第一个参数? [英] Why always add self as first argument to class methods?

查看:15
本文介绍了为什么总是将 self 添加为类方法的第一个参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
为什么你需要明确有Python 方法中的self"参数?

我理解为什么 self 总是是类方法的第一个参数,这完全有道理,但如果总是这样,那么为什么要为每个方法定义都输入 if 呢?为什么不让它在幕后自动完成?

I understand why self is always the first argument for class methods, this makes total sense, but if it's always the case, then why go through the hassle of typing if for every method definition? Why not make it something thats automatically done behind the scenes?

是为了清楚起见还是在某些情况下您可能不想将 self 作为第一个参数传递?

Is it for clarity or is there a situation where you may not want to pass self as the first argument?

推荐答案

因为显式优于隐式.通过使参数成为显式要求,您可以简化代码理解、内省和操作.它在 Python 常见问题解答.

Because explicit is better than implicit. By making the parameter an explicit requirement, you simplify code understanding, introspection, and manipulation. It's further expanded on in the Python FAQ.

此外,您可以定义类方法(将类而不是实例作为第一个参数),也可以定义静态方法(根本不要使用第一个"参数):

Moreover, you can define class methods (take a class instead of an instance as the first argument), and you can define static methods (do not take a 'first' argument at all):

class Foo(object):
    def aninstancemethod(self):
        pass

    @classmethod
    def aclassmethod(cls):
        pass

    @staticmethod
    def astaticmethod():
        pass

这篇关于为什么总是将 self 添加为类方法的第一个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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