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

动态语言 python C++ 对象 类型转换

lzcllyt 9 years, 9 months ago

 # -*- 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

未馴化D猫樣 answered 9 years, 9 months ago

Your Answer