首页 > 解决方案 > Python:实现__str__方法后保留对象的内存地址

问题描述

在类上实现str方法后如何保留对象的地址

class X:
    pass

x=X()
print(x)

#<__main__.X object at 0x000000A63773C5B0>hexadecimal value here I want to be able to bind to some variable 

class X:
    def __str__(self):
        objinfo='X object is located at {}'.format(argument here I wish to be hexadecimal value produced before __str__ method is implemented on a class)
        return objinfo

提前致谢

标签: pythonstringclassobject

解决方案


我认为这id(object)会给你一个对象的地址,用 . 将它转换为十六进制hex()

class X():
    def __init__(self,x):
        self.x = x
    def __str__(self):
        objinfo='X object is located at {}'.format(hex(id(self)))
        return objinfo

推荐阅读