Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么setattr和getattr允许空白?_Python_Attributes - Fatal编程技术网

Python 为什么setattr和getattr允许空白?

Python 为什么setattr和getattr允许空白?,python,attributes,Python,Attributes,假设我定义了这个类: class A: pass a = A() 现在很明显,我可以这样设置属性: a.x = 5 但是使用setattr,我可以给a属性提供名称中包含空格的属性 setattr(a, 'white space', 1) setattr(a, 'new\nline', None) dir(a)包含'whitespace'和'new\nline' 我无法使用运算符访问这些属性,因为它会引发语法错误: >>> a.white space File

假设我定义了这个类:

class A:
    pass

a = A()
现在很明显,我可以这样设置属性:

a.x = 5
但是使用
setattr
,我可以给
a
属性提供名称中包含空格的属性

setattr(a, 'white space', 1)
setattr(a, 'new\nline', None)
dir(a)
包含
'whitespace'
'new\nline'

我无法使用
运算符访问这些属性,因为它会引发
语法错误

>>> a.white space
  File "<interactive input>", line 1
    a.white space
                ^
SyntaxError: invalid syntax
>>> a.new\nline
  File "<interactive input>", line 1
    a.new\nline
              ^
SyntaxError: unexpected character after line continuation character
这种功能背后有什么原因吗?如果是,是什么


我们应该利用这一点,还是遵守PEP8中定义的标准?

对象属性仅仅是对象的
\uuuuuuuu dict\uuuuuuu
中定义的属性。如果您从这个角度考虑,那么在属性名中允许空白(或可以包含在
str
中的任何其他字符)是完全有意义的

>>> class X(object):
...  pass
... 
>>> x = X()
>>> setattr(x, 'some attribute', 'foo')
>>> x.__dict__
{'some attribute': 'foo'}
>>> x.__dict__['some attribute']
'foo'

也就是说,Python的语言语法不能在直接属性引用中使用空格,因为解释器不知道如何对程序源进行属性标记(解析)。我坚持使用可以通过直接属性引用访问的字符,除非您确实需要这样做。

它还允许破折号和大多数其他字符作为直接属性无效。确实如此。属性名只是一个为dict设置键的字符串。
>>> class X(object):
...  pass
... 
>>> x = X()
>>> setattr(x, 'some attribute', 'foo')
>>> x.__dict__
{'some attribute': 'foo'}
>>> x.__dict__['some attribute']
'foo'