在这里使用@property时,为什么PyCharm会发出警告? [英] Why does PyCharm raise a warning when using @property here?

查看:188
本文介绍了在这里使用@property时,为什么PyCharm会发出警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在教程中,出于使用@property的目的,我看到了两种类型的实例属性命名.这是显示两者示例的代码.它们的工作方式也似乎有所不同.

In tutorials I have seen two types of instance attribute naming for the purpose of using @property. Here is code showing examples of both. They also seem to work differently.

class A:
    def __init__(self, x):
        self.x = x

    @property
    def x(self):
        return self.__x

    @x.setter
    def x(self, x):
        if x > 1000:
            self.__x = 1000
        else:
            self.__x = x  # Instance attribute __x defined outside __init__

class B:
    def __init__(self, x):
        self._x = x

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, x):
        if x > 1000:
            self._x = 1000
        else:
            self._x = x

a = A(9999)
print(a.x)  # -> 1000

b = B(9999)  # -> 9999
print(b.x)
b.x = 9999
print(b.x)  # -> 1000

我更喜欢A类的行为,因为@ x.setter似乎在__init__中立即使用,但是那段代码在PyCharm中给了我警告(我将其作为注释).如果正确使用Python的属性设置器,为什么会出现警告? B类中没有警告.我能以某种方式在__init__中以与A类中相同的方式调用@ x.setter而不发出警告吗?

I like the behaviour of class A better as it seems that the @x.setter is used immediately in __init__, however that piece of code gives me a warning in PyCharm (I have it as a comment). Why would there be a warning if that is the proper use of a Python's property setter? There are no warnings in class B. Could I somehow call @x.setter in __init__ the same way as in class A without a warning?

推荐答案

似乎是PyCharm中的错误:

It seems to be a bug in PyCharm: https://youtrack.jetbrains.com/issue/PY-25263.

我发现的一个临时解决方案是在__init__中添加self._x = None.因此代码将是:

A temporary solution I found was to add self._x = None in the __init__. So the code would be:

class A:
    def __init__(self, x):
        self._x = None
        self.x = x

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, x):
        if x > 1000:
            self._x = 1000
        else:
            self._x = x


a = A(9999)
print(a.x)  # -> 1000

这篇关于在这里使用@property时,为什么PyCharm会发出警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆