Python: make function to be a bounded method
Python to be Function method Make
2023-09-11 14:16:16 时间
所有function都有 __get__ 用于实现绑定
__get__
class B: def __init__(self, v): self._v = v def v(self): return self._v def bind(instance, func, name=None): if name is None: name = func.__name__ bounded = func.__get__(instance, instance.__class__) setattr(instance, name, bounded) return bounded def double(self): return 2 * self._v print(getattr(B.v, '__get__')) print(B.v) b = B(55) print(bind(b, double)) print(b.double()) f = B.v.__get__(b, int) print(f, b) print(f()) print(f.__class__, )
types.MethodType
import types def f(self): print(self) class B: ... method = types.MethodType(f, B()) print(method) print(method())
functools.partial
import functools import types def f(self): print(self) class B: ... method = functools.partial(f, B()) print(method) print(method())
import functools import types def f(self): print(self) class B: ... b = B() b.method = (lambda self: lambda: f(self))(b) print(b.method) print(b.method())
相关文章
- Python 自动化中三种等待时间的详解~
- Python任意参数的数量/预习课python基础
- 使用python 搭建web服务器
- 学python能做什么兼职-初学Python到月入过万最快的兼职途径(纯干货)
- 零基础自学Python需要多长时间从入门到精通?学python能兼职挣钱吗?怎么挣钱?
- 【python实战】拒绝黄牛!我要用python原价冲周董演唱会~Python自动秒杀抢票脚本
- 132 python高级 - 正则表达式(表示字符)
- 82 python高级 - 元类
- Linux集群和自动化维3.3 Python的版本说明
- 启动简单的springboot项目报错:To display the conditions report re-run your..Web server failed to start
- Python 爬虫知识点 - 淘宝商品检索结果抓包分析(续二)
- Python 操作 mysql 数据库,并使用连接池
- Python 数据分析教程之如何验证线性回归的假设,线性回归的假设是什么?以及如何用python验证它们?
- Python地理空间栅格数据终极初学者指南您,全面了解的有关栅格文件、地理配准、元数据和 Rasterio Python 库的所有信息
- Python 使用PyMySql 库 连接MySql数据库时 查询中文遇到的乱码问题(实测可行) python 连接 MySql 中文乱码 pymysql库
- python开发面试问题
- 【Python】Python基础学习笔记
- 【Python】python扩展
- [Python]python+yaml三行代码完成配置文件灵活读取与warning:YAMLLoadWarning处理
- Python蓝桥杯训练:基本数据结构 [数组]——双指针法