方法下划线? [英] Method Underscores?

查看:90
本文介绍了方法下划线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于

内置方法名称,是否有使用尾随和前导双下划线的目的?我的印象是,下划线被认为是暗示某种伪私有化,但是使用

myclass.len()而不是myclass .__ len __()确实会导致Python

相当大的伤害?尽管我喜欢Python,但我不得不承认,我发现

这是语言中最unPythonic的语言之一。功能和密钥

反对Python的争论点。我在群组档案中搜索了关于这个

主题的讨论,但发现很少。每个人都有什么关于这个主题的想法?

解决方案



" Chris S. < CH ***** @ NOSPAM.udel.edu>写道:

是否有用于内置方法名称的尾随和前导双下划线的目的?我的印象是,下划线被认为暗示某种伪私有化,但是使用
myclass.len()而不是myclass .__ len __()真的会导致Python相当大的伤害吗?尽管我喜欢Python,但我不得不承认,我发现这是最unPythonic语言之一。功能和关键的争论点反对Python。我在群组档案中搜索了关于这个
主题的讨论,但发现很少。每个人对这个主题的想法是什么?



双下划线方法被认为是魔术方法。

下划线暗示他们可能会做些不同的事情。有点类似于C ++朋友运营商的



就.len()vs .__ len __()而言,它不应被称为

直接由用户代码; __len __()由len()

builtin间接调用(类似于其他__< op> __()方法,检查运算符模块中的常见

拼写)。


class foo:

def __len __(个体经营):

返回4


a = foo()

len(a)#like this

- Josiah


Chris S.< ch ***** @ NOSPAM.udel.edu>写道:

是否有用于内置方法名称的尾随和前导双下划线的目的?


它们表示方法是特殊的(不是''内置'')。一个

导致Python在某些情况下隐式调用它。


因此,例如,碰巧定义方法的类不会

开始表现得很奇怪当''iter''在某些

语言的未来版本中获得了特殊含义:如果它出现的特殊含义将是

而是穿上__iter__。这确实发生过(在2.2中)。

否则,你会遇到与特殊方法相同的问题

关键字:引入一个是_major_ undertaking因为它有风险

打破向后兼容性(内置名称没有那种风险;

它可能不是很明显,但有些反映会显示)。


((标记某类标识符的一般做法是使用

特殊字符将它们与其他字符区分开来)被称为stropping

并被引入在早期的Algol 60实现中,要区分

关键字与名称; Algol标准使用罗马字体与斜体

为目的,但这并没有很好地转化为打孔卡片!))

我的印象是下划线被认为意味着某种伪私有化,


仅限领先的下划线。中间的下划线意味着什么,

它只是一种从许多单词中制作标识符的风格;有些像

this_way,有些像那样。通常只使用尾随下划线

否则标识符将成为关键字,如''class_''或

''print_''(您需要一些约定)当你接口时,你需要接口外部库 - ctypes,COM,Corba,SOAP等等 - 因为

没有什么能阻止外部库定义

恰好与Python关键字冲突的名称)。领先和尾随双重

强调暗示特殊性。

但是会使用
myclass.len()而不是myclass .__ len __()真正导致Python
相当大的伤害?




如果您从头开始设计Python,那么权衡将是:

- 非拓扑特殊名称更容易阅读,但是

- 语言的未来发展将受到严重阻碍(或者说b $ b其他向后兼容性经常会被破坏)。


所以这是一个权衡,就像选择stropping或不是

barenames(标识符); Perl strops因为Larry Wall早期决定

他想要很多简单的进化(从EXEC到现在,还有一种在脚本语言中使用b / b
标识符的传统;有时

在_substitution_的幌子下,其中绑定的标识符不是

stropped但它需要stropping才能使用,如sh和tcl; Rexx和

Python故意拒绝这种传统以支持易读性。


我认为Guido的设计选择正确:所有的未折叠的全名

正常使用,无限制的关键字,每当关键字需要添加时都要支付价格(这很少),按惯例划分的特殊名称

(他们很方便)比一般的名字更为罕见,_and_增加

的特殊名称更常见。


关于具体的词汇糖问题,什么标点符号来到

用于这个stropping,我通过;两侧的双下划线是视觉上有侵略性的,但是其他选择可能已经很少了,但是后来我想这部分选择正是为了使得特殊性

特别名字脱颖而出。因为我不太可能很快就需要设计类似Python的语言,因此要确定如何划分

特殊名称,这是'幸福地多余让我决定;-)。

Alex


Chris S.写道:

有没有为内置方法名称使用尾随和前导双下划线的目的?我的印象是,下划线应该暗示某种伪私有化,


它们用于表示Python使用的特殊方法

在不知道你正在做什么的情况下不应该改变或覆盖。

但是会使用
myclass.len()而不是myclass .__ len __( )真的会对Python造成相当大的伤害吗?


想到它的一种方法是作为一种命名空间。 Python

需要一些特殊的名字方法,以便


打印一个== b


正常工作('' __eq__''或'__cmp__''用于比较,

和''_ _ _ _ _ _ _ _ _ _ _ _'''''* $ $ $ $
这些可能是看似正常的函数(含义)没有

领先和尾随下划线)但是那时候有人担心有人会意外地覆盖它。


通过以大多数人不会正常使用并且正式声明该范围为系统使用而保留的范围来使它们变得特别,该事故不会发生发生。

没有人会意外地做


def搜索(自我,名字):

....

self.str ="寻找 +名称


只是为了找到后者需要'str''来打印

实例的字符串化版本。

或者考虑另一种方式。假设每个人都决定

我们需要一个新的迭代协议(几年前假装这是一个

)。新协议需要一种新方法

名称。它应该被称为什么?


如果没有保留命名空间的子空间那么

任何选择都有可能干扰

现有代码。但是因为__+ ... +__是保留的,它很容易为__ iter __添加特殊含义。并且知道

没有现有代码会破坏。

在大多数情况下,这些方法的内置函数接口

不仅仅是转发呼叫。例如,iter()

支持第二个参数sentinel和fall-back支持

用于不提供__iter__的列表。


在几十种特殊方法中,有多少人会直接打电话给你?你不太可能会打电话给

__add __,__ mul __,__ lt__,......如果只是因为你会给b
$松散对给定操作的支持
<块引用类= post_quotes> (1).__添加__(2)
3分配(1).__添加__(2.0)
NotImplemented




我的猜测是你有len(),abs(),也许是iter(),

但不多。应该只有少数人有非特殊名称吗?或者所有特殊方法都应该具有

非特殊名称?如果第一个,为什么那么少?

如此特别?


你更喜欢-x还是x.inv()?

尽管我喜欢Python,但我不得不承认,我发现这是最unPythonic语言之一。功能和关键的争论点反对Python。我在群组档案中搜索了关于这个
主题的讨论,但发现很少。每个人对这个问题的想法是什么?




我没想到。我发现它有助于我不用担心

与特殊方法名称冲突。只要我没有使用__* * 2字我就可以随意使用我想要的任何东西。

如果我使用的话,甚至是保留字getattr / setattr / delattr。


有讨论,但我只在5年前从Guido发现了一个评论

说__用于

系统名称,大约2年后蒂姆·彼得斯说,

,你可以直接调用几种方法。

我的一篇帖子说我喜欢Python的这个特性

与Ruby相比,特殊方法在语法上与用户定义的方法无法区分。


Andrew
da***@dalkescientific.com


Is there a purpose for using trailing and leading double underscores for
built-in method names? My impression was that underscores are supposed
to imply some sort of pseudo-privatization, but would using
myclass.len() instead of myclass.__len__() really cause Python
considerable harm? As much as I adore Python, I have to admit, I find
this to be one of the language''s most "unPythonic" features and a key
arguing point against Python. I''ve searched for a discussion on this
topic in the groups archives, but found little. What are everyone''s
thoughts on this subject?

解决方案


"Chris S." <ch*****@NOSPAM.udel.edu> wrote:

Is there a purpose for using trailing and leading double underscores for
built-in method names? My impression was that underscores are supposed
to imply some sort of pseudo-privatization, but would using
myclass.len() instead of myclass.__len__() really cause Python
considerable harm? As much as I adore Python, I have to admit, I find
this to be one of the language''s most "unPythonic" features and a key
arguing point against Python. I''ve searched for a discussion on this
topic in the groups archives, but found little. What are everyone''s
thoughts on this subject?


Double underscore methods are considered "magic" methods. The
underscores are a hint that they may do something different. Kind of
like the C++ friend operators.

In terms of .len() vs .__len__(), it is not supposed to be called
directly by user code; __len__() is called indirectly by the len()
builtin (and similarly for the other __<op>__() methods, check common
spellings in the operator module).

class foo:
def __len__(self):
return 4

a = foo()
len(a) #like this
- Josiah


Chris S. <ch*****@NOSPAM.udel.edu> wrote:

Is there a purpose for using trailing and leading double underscores for
built-in method names?
They indicate that a method is special (not ''built-in''). One that
causes Python to call it implicitly under certain circumstances.

So, for example, a class which happened to define method iter would not
start behaving strangely when ''iter'' acquired a special meaning in some
future version of the language: the special meaning if it comes will be
instead put on __iter__ . This has indeed happened (in 2.2).
Otherwise, you''d have the same problem with special methods as you do
with keywords: introducing one is a _major_ undertaking since it risks
breaking backwards compatibility (built-in names do not have that risk;
it may not be obvious but some reflection will show that).

(( The general practice of marking some class of identifiers with
special characters to distinguish them from others is known as stropping
and was introduced in early Algol 60 implementations, to distinguish
keywords from names; the Algol standard used roman font versus italics
for the purpose, but that didn''t translate well to punched cards! ))
My impression was that underscores are supposed
to imply some sort of pseudo-privatization,
Leading-only underscores do. Underscores in the middle imply nothing,
it''s just a style of making an identifier from many words; some like
this_way, some like thatWay. Trailing-only underscore normally is used
when otherwise an identifier would be a keyword, as in ''class_'' or
''print_'' (you need some convention for that when you''re interfacing
external libraries -- ctypes, COM, Corba, SOAP, etc, etc -- since
nothing stops the external library from having defined a name which
happens to clash with a Python keyword). Leading AND trailing double
underscores imply specialness.
but would using
myclass.len() instead of myclass.__len__() really cause Python
considerable harm?



If you were designing Python from scratch, the tradeoff would be:
-- unstropped specialnames are easier to read, but
-- future evolution of the language will be severely hampered (or
else backwards compatibility will often get broken).

So it''s a tradeoff, just like the choice of stropping or not for
barenames (identifiers); Perl strops because Larry Wall decided early on
he wanted lots of easy evolution (there''s also a tradition of stropping
identifiers in scripting languages, from EXEC to the present; sometimes
under guise of _substitution_, where an identifier being bound is not
stropped but it needs stropping to be used, as in sh and tcl; Rexx and
Python deliberately reject that tradition to favour legibility).

I think Guido got that design choice right: unstropped barenames for all
normal uses, unstropped keywords, pay the price whenever a keyword needs
to be added (that''s rarely), stropped-by-convention specialnames
(they''re way rarer than barenames in general, _and_ the addition of
specialnames is more frequent).

On the specific lexical-sugar issue of what punctuation characters to
use for this stropping, I pass; the double underscores on both sides are
a bit visually invasive, other choices might have been sparer, but then
I guess that part of the choice was exactly to make the specialness of
specialnames stand out starkly. Since it''s unlikely I''ll soon need to
design a Python-like language and thus to decide on exactly how to strop
specialnames, it''s blissfully superfluous for me to decide;-).
Alex


Chris S. wrote:

Is there a purpose for using trailing and leading double underscores for
built-in method names? My impression was that underscores are supposed
to imply some sort of pseudo-privatization,
They are used to indicate special methods used by Python
that shouldn''t be changed or overridden without knowing what
you are doing.
but would using
myclass.len() instead of myclass.__len__() really cause Python
considerable harm?
One way to think of it is as a sort of namespace. Python
needs some specially names methods so that

print a == b

works correctly (''__eq__'' or ''__cmp__'' for the comparison,
and ''__str__'' for the stringification for printing).
These could be normal looking functions (meaning without
leading and trailing underscores) but then there''s
the worry that someone will override that by accident.

By making them special in a way that most people wouldn''t
use normally and formally stating that that range is
reserved for system use, that accident won''t happen.
No one will accidently do

def search(self, name):
....
self.str = "Looking for " + name

only to find latter that ''str'' is needed for printing
the stringified version of the instance.

Or consider the other way around. Suppose everyone decides
we need a new protocol for iteration (pretend this is a
few years ago). The new protocol requires a new method
name. What should it be called?

If there isn''t a reserved subspace of the namespace then
any choice made will have a chance of interfering with
existing code. But since "__"+...+"__" is reserved, it
was easy to add special meaning to "__iter__" and know
that no existing code would break.
In most cases the builtin function interface to those methods
does more than forward the call. For example, iter()
supports both a 2nd parameter sentinel and fall-back support
for lists that don''t provide an __iter__.

Of the several dozen special methods, how many would
you really call directly? It''s unlikely you would call
__add__, __mul__, __lt__, ... if only because you would
loose the support for the given operation

(1).__add__(2) 3 (1).__add__(2.0) NotImplemented



My guess is you''ll have len(), abs(), maybe iter(),
but not many more. Should only that handful have
non-special names or should all special methods have
non-special names? If the first, why is that handful
so special?

Do you prefer -x or x.inv() ?

As much as I adore Python, I have to admit, I find
this to be one of the language''s most "unPythonic" features and a key
arguing point against Python. I''ve searched for a discussion on this
topic in the groups archives, but found little. What are everyone''s
thoughts on this subject?



I''ve not thought so. I find it helps me not worry about
conflicting with special method names. So long as I
don''t use the "__"*2 words I''m free to use whatever I want.
Even reserved words if I use getattr/setattr/delattr.

There has been discussion, but I only found a comment
from Guido about 5 years ago saying the "__" are meant for
system names and from Tim Peters about 2 years back saying
that there are only a few methods you might call directly.
And a post of mine saying that I like this feature of Python
compared to in Ruby where special methods are syntactically
indistinguishable from user-defined methods.

Andrew
da***@dalkescientific.com


这篇关于方法下划线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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