玩蛇网提供最新Python编程技术信息以及Python资源下载!

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)

那么 pidppid 相同,且 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 newinstance

p1=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

玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/wenda/wd19500.html

相关文章 Recommend

玩蛇网Python互助QQ群,欢迎加入-->: 106381465 玩蛇网Python新手群
修订日期:2017年05月18日 - 15时41分00秒 发布自玩蛇网

您现在的位置: 玩蛇网首页 > Python问题解答 > 正文内容
我要分享到:

必知PYTHON教程 Must Know PYTHON Tutorials

必知PYTHON模块 Must Know PYTHON Modules