问题
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
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?
回答1:
It seems to be a bug in PyCharm: https://youtrack.jetbrains.com/issue/PY-25263.
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
来源:https://stackoverflow.com/questions/45745248/why-does-pycharm-raise-a-warning-when-using-property-here