为什么从属性名称的开头剥离前导空格?(Why are leading spaces stripped from the beginning of attributes names?)

编程入门 行业动态 更新时间:2024-10-24 14:16:09
为什么从属性名称的开头剥离前导空格?(Why are leading spaces stripped from the beginning of attributes names?)

假设我们在Python 2.7或3.5中有一个虚拟类。 我们想为实例分配一些属性:

>>> class X(object): ... pass ... >>> x = X()

让我们使用setattr()设置一个带前导空格的变量:

>>> setattr(x, ' foo', 'bar') # ^^^^^^^^^^^^^^^^^^ >>> x.__dict__ {' foo': 'bar'} # ^^^^^^^^^^^^^^^^^^

现在让我们直接分配值,而不用setattr() :

>>> x. hello = 'bye' # ^^^^^^^^^^^^^^^^ >>> x.__dict__ {' foo': 'bar', 'hello': 'bye'} # ^^^^^ # leading spaces have been removed!

使用instance.attribute = value格式删除前导空格!

在PEP 8指示之后,这最后的行为似乎是期望的行为:

方法名称和实例变量

使用函数命名规则:小写,必要时用下划线分隔,以提高可读性。

但是,我们刚刚看到使用setattr()允许我们规避这个规则。 此外,除非使用getattr() ,否则getattr()获取具有前导空格的属性,因为它无法使用带有instance.attr = value语法的前导空格分配变量。

为什么允许这样做?

Say we have a dummy class in Python 2.7 or 3.5. We want to assign some attributes to an instance:

>>> class X(object): ... pass ... >>> x = X()

Let's set one variable with leading spaces using setattr():

>>> setattr(x, ' foo', 'bar') # ^^^^^^^^^^^^^^^^^^ >>> x.__dict__ {' foo': 'bar'} # ^^^^^^^^^^^^^^^^^^

Now let's do the same assigning the value directly, without setattr():

>>> x. hello = 'bye' # ^^^^^^^^^^^^^^^^ >>> x.__dict__ {' foo': 'bar', 'hello': 'bye'} # ^^^^^ # leading spaces have been removed!

The leading spaces get removed by using the instance.attribute = value format!

This last behaviour seems like the desired one after PEP 8 indications:

Method Names and Instance Variables

Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.

However, we just saw that using setattr() allowed us to circumvent this rule. Also, this makes it impossible to get an attribute with leading spaces unless getattr() is used, as much as it makes it impossible to assign a variable with leading spaces with the instance.attr = value syntax.

Why is this allowed?

最满意答案

在第二种情况下没有任何空格,因为在分析阶段,在分配完成之前,所有空格都被丢弃。

考虑到Python强调可读性,例如,这可以允许跨越多行(在点之后打破行)并且仍然具有工作代码:

>>> str. \ ... lower <method 'lower' of 'str' objects>

There isn't any whitespace in the second case as the spaces are all discarded in the parsing phase, way before the assignment is done.

Considering Python's emphasis on readability, this can for example allow to run across multiple lines (breaking the line after a dot) and still have working code:

>>> str. \ ... lower <method 'lower' of 'str' objects>

更多推荐

本文发布于:2023-07-28 18:45:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1307995.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:从属性   前导   空格   开头   名称

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!