【发布时间】:2021-03-13 12:52:27
【问题描述】:
由于可以在类、方法、变量的标识符中使用 unicode 字符,因此我越来越多地使用它们。我不知道这是不是一个好主意,但它使代码更具可读性(例如,您现在可以使用import numpy as np; π = np.pi; area = r**2 * π!)
现在我注意到以下行为(在 Python 3.8.5 中):
我可以通过以下方式定义一个类A:
>>> class A:
... def x(self):
... print('x')
... def ξ(self):
... print('ξ')
... def yₓ(self):
... print('yₓ')
并且可以访问所有方法:
>>> a = A()
>>> a.x()
x
>>> a.ξ()
ξ
>>> a.yₓ()
yₓ
问题来了,如果我想使用getattr() 来访问它们:
>>> attr = getattr(a, 'x')
>>> attr()
x
>>> attr = getattr(a, 'ξ')
>>> attr()
ξ
>>> attr = getattr(a, 'yₓ')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'yₓ'
'A' object has no attribute 'yₓ'
- 为什么
getattr(a,'ξ')有效,而getattr(a, 'yₓ')无效?
我注意到了
>>> dir(a)
[…, 'x', 'yx', 'ξ']
-
为什么
'ξ'被保留,而'yₓ'却默默地转换为'yx'?哪些是“安全”字符,可以使用哪些,让getattr()成功? -
有没有办法让我可以使用
yₓ?
顺便说一句,yₓ 可以使用,但y₂ 给出了SyntaxError: invalid character in identifier
- 为什么我根本不能使用
y₂?
我知道,解决方法是不使用任何那些花哨的字符,但其中一些使代码真正更具可读性(至少在我看来!)......
【问题讨论】:
-
作为一般规则,问问自己:“这个字符是非英语语言的母语脚本的一部分吗?”如果答案是“否”,请谨慎行事。
标签: python python-3.x