继承int以获得十六进制表示 [英] subclassing int to attain a Hex representation

查看:158
本文介绍了继承int以获得十六进制表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我想访问所有标准的python int操作符,例如 __和__ __ xor __ 等,结果终于打印出来了,我希望它以十六进制格式表示。 (有点像把我的计算器放到十六进制模式)

pre $ class $($)
def __repr __(self) :
返回0x%x%self
__str __ = __ repr__#这当然有助于打印

if __name __ ==__ main__:
print Hex(0x1abe11ed )^ Hex(440720179)
print Hex(Hex(0x1abe11ed)^ Hex(440720179))

理想情况下,两行输出应该是十六进制:0xfacade,但是第一个输出十进制:16435934



有什么想法?



您可以自己写一个Mixin:

  class IntMathMixin:
def __add __(self,other):
返回类型(self)(int(self).__ add __(int (other)))
#...其他人的模拟

然后像使用它一样这个:

$ p $ class Hex(IntMathMixin,int):
def __repr __(self):
return为0x% x%self
__str __ = __ repr__


Basically I want to have access to all standard python int operators, eg __and__ and __xor__ etc, specifically whenever the result is finally printed I want it represented in Hex format. (Kind of like putting my calculator into Hex mode)

class Hex(int):
  def __repr__(self):
    return "0x%x"%self
  __str__=__repr__ # this certainly helps with printing

if __name__=="__main__":
  print Hex(0x1abe11ed) ^ Hex(440720179)
  print Hex(Hex(0x1abe11ed) ^ Hex(440720179))

Ideally BOTH line of output should be hexadecimal: 0xfacade, however the first one yields decimal: 16435934

Any ideas?

解决方案

In response to your comment:

You could write a Mixin by yourself:

class IntMathMixin:
    def __add__(self, other):
        return type(self)(int(self).__add__(int(other)))
    # ... analog for the others

Then use it like this:

class Hex(IntMathMixin, int):
    def __repr__(self):
         return "0x%x"%self
    __str__=__repr__ 

这篇关于继承int以获得十六进制表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆