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'