python get set
时间: 2023-12-06 12:38:40 浏览: 36
以下是Python中get和set的介绍和演示:
在Python中,get和set是属性访问器,用于控制对类属性的访问。get和set方法可以通过@property和@<attribute>.setter装饰器来实现。
1.使用@property装饰器实现get方法:
```python
class MyClass:
def __init__(self, value):
self._value = value
@property
def value(self):
print('Getting value...')
return self._value
```
在上面的代码中,我们定义了一个名为value的属性,并使用@property装饰器将其转换为只读属性。当我们访问value属性时,会自动调用value方法。
2.使用@<attribute>.setter装饰器实现set方法:
```python
class MyClass:
def __init__(self, value):
self._value = value
@property
def value(self):
print('Getting value...')
return self._value
@value.setter
def value(self, value):
print('Setting value...')
self._value = value
```
在上面的代码中,我们使用@value.setter装饰器定义了一个名为value的setter方法。当我们设置value属性时,会自动调用value方法。
3.使用get和set方法实现:
```python
class MyClass:
def __init__(self, value):
self._value = value
def get_value(self):
print('Getting value...')
return self._value
def set_value(self, value):
print('Setting value...')
self._value = value
value = property(get_value, set_value)
```
在上面的代码中,我们定义了一个名为value的属性,并使用property函数将其转换为只读属性。当我们访问value属性时,会自动调用get_value方法。当我们设置value属性时,会自动调用set_value方法。