编写Python属性显示意外的行为

问题描述 投票:0回答:1

以下是从我的Python 2.7的控制台输出。我写类似的事情在Python 3所有的时间和它的作品如预期。那么,为什么我允许做如下重新分配(在Python 2.7):

>>> class Fola:
...     def __init__(self,a,b):
...         self._a = a
...         self._b = b
...     @property
...     def a(self):
...         return self._a
... 
>>> m = Fola('mlem','blib')
>>> m.a
'mlem'
>>> m._b
'blib'
>>> m._a
'mlem'
>>> m.a = 'plip'
>>> m.a
'plip'
>>> m._a
'mlem'
>>> m._b
'blib'
python-2.7 python-3.x properties decorator python-decorators
1个回答
0
投票
>>> class Fola(object):
...   def __init__(self,a,b):
...     self._a = a
...     self._b = b
...   @property
...   def a(self):
...     return self._a
... 
>>> m = Fola(1,2)
>>> m.a
1
>>> m._b
2
>>> m.a
1
>>> m._a
1
>>> m.a = 10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
© www.soinside.com 2019 - 2024. All rights reserved.