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'>

阅读 6.4k
1 个回答
# -*- 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
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题