【问题标题】:Writing python property shows unexpected behaviour编写 python 属性显示意外行为
【发布时间】:2017-12-17 17:47:02
【问题描述】:

以下是我的 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】:
    >>> 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
    

    【讨论】:

      猜你喜欢
      • 2018-11-29
      • 2016-09-16
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-27
      相关资源
      最近更新 更多