python 中描述符@property property 大概的样子

class MyProperty:

def init(self, fget=None, fset=None, fdel=None):

self.fget = fget # getter 方法

self.fset = fset # setter 方法

self.fdel = fdel # deleter 方法

def get(self, instance, owner):

if instance is None:

return self

if self.fget is None:

raise AttributeError("不可读")

return self.fget(instance)

def set(self, instance, value):

if self.fset is None:

raise AttributeError("不可写")

self.fset(instance, value)

def delete(self, instance):

if self.fdel is None:

raise AttributeError("不可删除")

self.fdel(instance)

def setter(self, func):

self.fset = func

return self # 返回自己,支持链式调用

class User:

def init(self, name):

self._name = name

@MyProperty # 等价于 name = MyProperty(name)

def name(self):

return self._name

@name.setter

def name(self, value):

self._name = value

u = User("张三")

print(u.name) # 调用 get

u.name = "李四" # 调用 set

print(u.name) # 李四

相关推荐
用户8356290780513 小时前
Python 实现 PDF 文件加密与解密方法
后端·python
用户8356290780513 小时前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
你好潘先生11 小时前
别再记命令了,用 yeero do 说句人话就能跑脚本,而且不烧 token
服务器·python·命令行
Agent_大师11 小时前
WebSocket 行情重连成功,K线缺口不会自动消失
python
荣码11 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
copyer_xyf11 小时前
FastAPI 如何连接 MySQL
后端·python
apocelipes1 天前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
用户8356290780511 天前
使用 Python 在 PDF 中创建与管理书签
后端·python
MeixianAgent1 天前
Python 回测数据入口怎么验?历史 K 线入库前先做 5 个检查
后端·python
咕白m6251 天前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python