python - getattr 和 unicode 属性

标签 python python-3.x

自从可以在类、方法、变量的标识符中使用 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ₓ'
  1. 为什么 getattr(a,'ξ') 有效,但 getattr(a, 'yₓ') 无效?

我注意到了

>>> dir(a)
[…, 'x', 'yx', 'ξ']
  1. 为什么 'ξ' 被保留,但 'yₓ' 默默地转换为 'yx'?可以使用哪些“安全”字符,以便 getattr() 成功?

  2. 有没有办法让我可以使用yₓ

顺便说一句,可以使用 yₓ,但是 y₂ 给出了一个 SyntaxError: invalid character in identifier

  1. 为什么我根本不能使用 y₂

我知道,解决方法是不使用任何那些花哨的字符,但其中一些确实使代码更具可读性(至少在我看来是这样!)...

最佳答案

非 ASCII 标识符在 PEP 3131 中定义.在其中,它说:

The entire UTF-8 string is passed to a function to normalize the string to NFKC

您可以使用 unicodedata.normalize 自行测试:

unicodedata.normalize("NFKC", 'ξ') # 'ξ'
unicodedata.normalize("NFKC", 'yₓ') # 'yx'

NFKC is very complicated, but you should be able to find safe characters with a loop.

关于python - getattr 和 unicode 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65093243/

相关文章:

Python 中的正则表达式删除逗号和空格

python - pandas - 基于子串出现次数的表达方法

python - 在 Python 中获取字符串的前 n 个字符的最佳方法

python - Jinja2 网络自动化 - 增加一个变量(子网+1)

python - QTreeWidget如何给子项添加复选框?

python-3.x - 在 urllib3 中,HTTP 请求挂起...但在curl 中则不然

Python Ctypes 双解引用指针

python - 将索引转换为日期时间并获取第 2 列最大值的时间

python - 如何使用 python 3.x 执行多项式加法和乘法?

python - 为什么我的想法在 python2 中不起作用?