Skip to main content
 首页 » 编程设计

python :为什么 setter和getter 如何快速设置属性

2025年05月04日16birdshome

<分区>

Possible Duplicate:
What is the benefit to using a ‘get function’ for a python class?

我刚开始读Python,但我想知道为什么Python根本不需要setter和getter?它已经有像属性一样的对象变量

考虑

class C(object): 
    def _init_(self): 
        self._x = None 
 
    def get_x(self): 
        return self._x 
 
    def set_x(self, value): 
        self._x = valu 
    x = property(get_x, set_x) 

我们可以只使用 C.x = "value"来做我们想做的事情吗?属性(property)的好处是什么?

顺便说一句,以这种方式创建 property/setter/getter 对我来说很麻烦,有什么办法可以简化它吗?喜欢

class C() 
   has_attributes("x", "y", "z")