python3xiaobaike_2020/chapter7/7-4 python3小白课:用property函数定义属性.md
2025-04-20 23:22:14 +08:00

48 lines
2.0 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# python3小白课用property函数定义属性
除了我们可以直接设定实例变量之外,我们在定义类的时候,还可以定义一些获取、设置等的专门的方法,将这些方法放到`property`参数中,可以让实例变量拥有这些属性。
这么说可能大家听得不是太明白,我们先来看一眼`property`函数(属性)的语法格式和说明,再来举例子:
property函数的语法格式为
```python
property(fget=None, fset=None, fdel=None, doc=None)
```
这里四个参数fget表示获取方法fset表示赋值方法fdel表示删除属性时调用的方法使用`del 实例名.属性名`可以删除属性比较少用doc表示说明文档是一个字符串。你可以传入0-4个参数如果没有传入的参数表示不允许对那个属性做那样的事。比如传入0个参数表示该属性既不能读也不能写又比如传入1个参数表示为只读属性。以此类推。
下面我们直接来看一个例子来理解吧。
```python
# coding:utf-8
class Student:
def getname(self):
return self.name
def setname(self, name):
print("进行了设置")
self.name = name
this_name = property(getname, setname)
s = Student()
s.this_name = "小白白"
print(s.this_name)
```
如上的代码,我们设定了一个可以读写的属性`this_name`,为了跟`name`进行区别我增加了前缀后续在进行设置和获取的时候会分别调用setname赋值时会调用那个我额外补的print函数你也可以把print函数改成一些赋值前的前置验证啊检查啊什么的达到不符合条件就无法赋值的目的和getname方法。
### 单词释义
| 单词 | 释义 |
| -------- | ------------------ |
| property | 性质,属性 |
| get | 获取 |
| set | 设置 |
| del | delete删除的简写 |
| doc | document文档的简写 |
| this | 这个,这一个 |