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

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

问题描述

可能重复:
为什么您需要明确拥有将"self"参数转换为Python方法?

Possible Duplicate:
Why do you need explicitly have the "self" argument into a Python method?

我了解为什么self总是 类方法的第一个参数,这很有意义,但是如果总是这样,那么对于每个方法定义,为什么都要麻烦键入呢?为什么不做一些在幕后自动完成的事情?

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天全站免登陆