Python - @property 和 __init__() 中的设置有什么区别? [英] Python - what's the difference between @property and setting in __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)
这篇关于Python - @property 和 __init__() 中的设置有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!