首页 > 解决方案 > __getattr__ 的奇怪问题,其中项目字符串在调用期间被更改

问题描述

出于某种奇怪的原因,对于特定字符,它似乎__getattr__以不可预知的方式改变了项目的价值。

这是一个完整的可运行示例:

class blah(object):
    def __getitem__(self,item):
        print(item)
        print(list([ord(s) for s in item]))

    def __getattr__(self, item):
        print(item)
        print(list([ord(s) for s in item]))


b=blah()

print("Index...")
b['ϕ']

print("__getattr__...")
b.ϕ

print("getattr()...")
getattr(b,'ϕ')

哪个输出:

Index...
ϕ
[981]
__getattr__...
φ
[966]
getattr()...
ϕ
[981]

(注意角色在__getattr__通话中发生了变化,而不是在其他人中)。例如,并非所有角色都会发生这种情况

print("Index...")
b['θ']

print("__getattr__...")
b.θ

print("getattr()...")
getattr(b,'θ')

产量

Index...
θ
[952]
__getattr__...
θ
[952]
getattr()...
θ
[952]

想法?

标签: python

解决方案


推荐阅读