Python - @property 和 __init__() 中的设置有什么区别?

Python - @property 和 __init__() 中的设置有什么区别?

问题描述:

无法从有关此主题的其他线程中直接得到答案:

Couldn't quite get a straight answer from other threads on this one:

在 Python 中,使用的主要区别是什么

In Python, what's the main difference between using

class Foo(object):
  def __init__(self, x):
    self.x = x

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

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

从外观上看,以这种方式使用@property 会使 x 只读……但也许有人有更好的答案?谢谢/弗雷德

By the looks of it using @property in this way makes x read-only.. but maybe someone has a better answer? Thanks /Fred

例如,是的,这允许您拥有只读属性.此外,属性可以让您看起来拥有比实际更多的属性.考虑一个带有 .radius.area 的圆.可以根据半径计算面积,而不必同时存储

For your example, yes this allows you to have read-only attributes. Further, properties can allow you to seem to have more attributes than you actually do. Consider a circle with .radius and .area. The area can be calculated based on the radius, rather than having to store both

import math

class Circle(object):
    def __init__(self, radius):
        self.radius = radius

    @property
    def area(self):
        return math.pi * (self.radius ** 2)