假设我们在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>更多推荐
发布评论