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

查看:34
本文介绍了为什么你需要明确地拥有“自我"?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 中有意的语言设计决定还是有一些实现细节需要将self"作为参数传递?

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