Python有与reinterpret_cast类同的机制吗,,嗯这里“类似
Python有与reinterpret_cast类同的机制吗,,嗯这里“类似
嗯这里“类似”不是指和 C++ 的 reinterpret_cast 一模一样,是这个意思:
假设我有以下两个类:
class Point1(object): def __init__(self, x, y): (self._x, self._y) = (x, y) def __str__(self): return "(%d, %d)" % (x, y)class Point2(object): def __init__(self, y, x): (self._x, self._y) = (x, y) def __str__(self): return "(%d, %d)" % (y, x)
那么是否有一个函数或运算符 reinterpret_cast,使得若:
p = Point1(233, 2333)pid = id(p)pp = reinterpret_cast(p, Point2)ppid = id(pp)pps = str(pp)t = type(pp)
那么 pid 和 ppid 相同,且 pps 是 '(2333, 233)' 以及 t 是 <class '__main__.Point2'>
# -*- coding:utf-8 -*-class Point1(object): def __init__(self, x, y): (self._x, self._y) = (x, y) def __str__(self): return "(%d, %d)" % (self._x, self._y)class Point2(object): def __init__(self, y, x): (self._x, self._y) = (x, y) def __str__(self): return "(%d, %d)" % (self._y, self._x)def reinterpret_cast_like(instance,cls): newinstance=instance newinstance.__class__=cls return newinstancep1=Point1(1,2)p2=reinterpret_cast_like(p1,Point2)print id(p1),id(p2),p2,type(p2)
执行结果
39093968 39093968 (2, 1) <class '__main__.Point2'>Process finished with exit code 0
编橙之家文章,
相关内容
- 请python高手帮我看看这段python代码中函数setter的用意,
- apache运行webpy项目遇到换行符无故增加的恼人问题,a
- Pyramid框架对于Audit审计功能应用参考书箱有什么?,py
- python3版本 tkinter gui写出来的程序最小化到系统托盘,
- 为什么python在eclipse中执行os命令不能正常运行,python
- Python pip安装需要再下载一次pip吗,pythonpip,我的pip的版
- Real Python PDF学习文档求分享,,这3个教程的名称是:C
- Python金山快盘API进行上传操作,返回405是什么原因,
- 代码中gunicorn reload选项无效是什么原因,gunicornreload,
- python有类与文件应用的规范吗,python应用规范,PHP的编码
评论关闭