python 是否有类似 reinterpret_cast 的机制?

发布于 2022-08-29 19:14:46 字数 807 浏览 18 评论 0

嗯这里“类似”不是指和 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'>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

伴我心暖 2022-09-05 19:14:46
# -*- 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文