为什么python对某些事情使用两个下划线? [英] Why does python use two underscores for certain things?

查看:54
本文介绍了为什么python对某些事情使用两个下划线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对实际的编程语言还很陌生,Python 是我的第一个.我对 Linux 有点了解,足以得到一份暑期工作(我还在上高中),而且在工作中,我有很多空闲时间用来学习 Python.

不过,有一件事一直让我着迷.当您使用诸如

之类的表达式时,Python 中到底有什么不同?

x.__add__(y) <==>x+yx.__getattribute__('foo') <==>x.foo

我知道方法的作用和内容,我知道它们做了什么,但我的问题是:上面的那些双下划线方法与它们看起来更简单的等效方法有何不同?

P.S.,我不介意被讲授编程历史,事实上,我觉得了解它非常有用:) 如果这些主要是 Python 的历史方面,请随意开始.

解决方案

嗯,程序员的能力是好的,所以应该有一种方法来自定义行为.像运算符重载(__add____div____ge__、...)、属性访问(__getattribute____getattr__(这两个是不同的)、__delattr__、...)等.在许多情况下,像运算符一样,通常的语法以 1:1 的比例映射到相应的方法.在其他情况下,有一个特殊的过程在某些时候涉及调用相应的方法 - 例如,__getattr__ 仅在对象没有请求的属性和 __getattribute__ 时调用code> 未实现或引发 AttributeError.其中一些是非常高级的主题,可以让您深入了解对象系统的内脏,并且很少需要.因此无需全部学习,只需在需要/想了解时查阅参考资料即可.说到参考,这里是.

I'm fairly new to actual programming languages, and Python is my first one. I know my way around Linux a bit, enough to get a summer job with it (I'm still in high school), and on the job, I have a lot of free time which I'm using to learn Python.

One thing's been getting me though. What exactly is different in Python when you have expressions such as

x.__add__(y) <==> x+y
x.__getattribute__('foo') <==> x.foo

I know what methods do and stuff, and I get what they do, but my question is: How are those double underscore methods above different from their simpler looking equivalents?

P.S., I don't mind being lectured on programming history, in fact, I find it very useful to know :) If these are mainly historical aspects of Python, feel free to start rambling.

解决方案

Well, power for the programmer is good, so there should be a way to customize behaviour. Like operator overloading (__add__, __div__, __ge__, ...), attribute access (__getattribute__, __getattr__ (those two are differnt), __delattr__, ...) etc. In many cases, like operators, the usual syntax maps 1:1 to the respective method. In other cases, there is a special procedure which at some point involves calling the respective method - for example, __getattr__ is only called if the object doesn't have the requested attribute and __getattribute__ is not implemented or raised AttributeError. And some of them are really advanced topics that get you deeeeep into the object system's guts and are rarely needed. So no need to learn them all, just consult the reference when you need/want to know. Speaking of reference, here it is.

这篇关于为什么python对某些事情使用两个下划线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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