为什么您需要明确拥有“自我"? Python方法中的参数? [英] Why do you need explicitly have the "self" argument in a Python method?

查看:69
本文介绍了为什么您需要明确拥有“自我"? Python方法中的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中的类上定义方法时,它看起来像这样:

When defining a method on a class in Python, it looks something like this:

class MyClass(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

但是在某些其他语言中,例如C#,您可以使用"this"关键字来引用该方法所绑定的对象,而无需在方法原型中将其声明为参数.

But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declaring it as an argument in the method prototype.

这是Python中的有意语言设计决定,还是有一些实现细节需要传递自我"作为自变量?

Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument?

推荐答案

我喜欢引用Peters的Python Zen. 显式比隐式好."

I like to quote Peters' Zen of Python. "Explicit is better than implicit."

在Java和C ++中,可以推断出this.,除非您具有无法推断的变量名.因此,您有时需要它,有时则不需要.

In Java and C++, 'this.' can be deduced, except when you have variable names that make it impossible to deduce. So you sometimes need it and sometimes don't.

Python选择使这种事情变得明确,而不是基于规则.

Python elects to make things like this explicit rather than based on a rule.

此外,由于没有暗示或假设,因此公开了部分实现. self.__class__self.__dict__和其他内部"结构显然可用.

Additionally, since nothing is implied or assumed, parts of the implementation are exposed. self.__class__, self.__dict__ and other "internal" structures are available in an obvious way.

这篇关于为什么您需要明确拥有“自我"? Python方法中的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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