Skip to main content
 首页 » 编程设计

python之PyCharm 在有效代码上说 "Property can not be read"

2025年02月15日7cyq1162

让我们看下面的代码:

import typing 
 
def make_getter(field: str) -> typing.Callable[['A'], int]: 
    def getter(self: 'A') -> int: 
        return int(self.dict[field]) 
    return getter 
 
def make_setter(field: str) -> typing.Callable[['A', int], None]: 
    def setter(self: 'A', value: int): 
        self.dict[field] = str(value) 
    return setter 
 
class A: 
    def __init__(self, d: dict): 
        super().__init__() 
        self.dict = d 
 
    get_x = make_getter('foo') 
    set_x = make_setter('foo') 
    x = property(get_x, set_x) 
 
    def get_y(self) -> int: 
        return int(self.dict['bar']) 
    def set_y(self, value: int): 
        self.dict['bar'] = str(value) 
    y = property(get_y, set_y) 

我定义了 2 个属性:x 和 y。两者都应该工作正常,没有任何问题,两者应该有相同的行为。 接下来,代码如下:

a = A(dict()) 
a.x = 10 
print(a.x) 
a.y = 20 
print(a.y) 

PyCharm 编辑器在 a.x 上显示:“无法读取属性”。 但是这段代码执行得很好,没有任何问题。

第一个想法是 PyCharm 错误地推断类型。 But look at this short video I recorded.我看不出类型有任何问题。

还有:

print(repr(a.get_x), repr(a.get_y)) 
print(repr(A.get_x), repr(A.get_y)) 
print(repr(A.x), repr(A.y)) 

它的输出:

<bound method make_getter.<locals>.getter of <__main__.A object at 0x7f7d25145f28>> <bound method A.get_y of <__main__.A object at 0x7f7d25145f28>> 
<function make_getter.<locals>.getter at 0x7f7d25132e18> <function A.get_y at 0x7f7d25132f28> 
<property object at 0x7f7d25143c78> <property object at 0x7f7d25143cc8> 

...所以 x 和 y 几乎等同。

为什么 PyCharm 这么说?我做错了什么或者是某种错误?如何修复它(不禁用此类警告)?

请您参考如下方法:

设置为 __init__(self, d: dict) -> None 现在似乎可以工作了。