我知道在 python 中使用 getter 和 setter 不是 pythonic。应该使用属性装饰器。但我想知道以下情况 -
我有一个用一些实例属性初始化的类。然后稍后我需要将其他实例属性添加到类中。如果我不使用 setter,那么我必须在类之外的所有地方编写 object.attribute = value
。该类将没有 self.attribute
代码。当我需要跟踪类的属性时(因为它们散布在类外的代码中),这不会成为问题吗?
最佳答案
一般来说,您甚至不应该使用属性。在绝大多数情况下,简单的属性都可以正常工作:
class X:
pass
>>> x = X()
>>> x.a
Traceback (most recent call last):
# ... etc
AttributeError: 'X' object has no attribute 'a'
>>> x.a = 'foo'
>>> x.a
'foo'
仅当您需要在访问属性时做一些工作时才应使用属性:
import random
class X:
@property
def a(self):
return random.random()
>>> x = X()
>>> x.a
0.8467160913203089
如果您还需要能够分配给一个属性,定义一个 setter 很简单:
class X:
@property
def a(self):
# do something clever
return self._a
@a.setter
def a(self, value):
# do something even cleverer
self._a = value
>>> x = X()
>>> x.a
Traceback (most recent call last):
# ... etc
AttributeError: 'X' object has no attribute '_a'
>>> x.a = 'foo'
>>> x.a
'foo'
请注意,在每种情况下,客户端代码访问特性或特性的方式完全相同。没有必要让你的类“面向 future ”,以防止在某些时候你可能想要做一些比简单的属性访问更复杂的事情,所以没有理由编写属性、getter 或 setter ,除非你确实需要它们现在。
有关属性、getter 和 setter 的惯用 Python 和其他一些语言之间的差异的更多信息,请参阅:
- Why don't you want getters and setters?
- Python is not Java (尤其是“Getters and setters are evil”部分)
关于python - 我应该使用属性还是 getter 和 setter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43896134/