为什么Python调用_str而不是返回长值
我有一个简单的类,它可以长时间扩展以接受带有值修饰符的字符串(即“10m”将是1024*1024*10) 我有一个为什么Python调用_str而不是返回长值,python,python-2.7,Python,Python 2.7,我有一个简单的类,它可以长时间扩展以接受带有值修饰符的字符串(即“10m”将是1024*1024*10) 我有一个\uuuu str\uuuu函数,它打印传入的原始值(即如果传入了“10m”,则返回“10m”) 问题是,当我调用诸如以下内容时: >>> printf("%d" % Size('10m')) 我得到以下信息 SystemError: ../Objects/stringobject.c:4044: bad argument to internal functio
\uuuu str\uuuu
函数,它打印传入的原始值(即如果传入了“10m”,则返回“10m”)
问题是,当我调用诸如以下内容时:
>>> printf("%d" % Size('10m'))
我得到以下信息
SystemError: ../Objects/stringobject.c:4044: bad argument to internal function
显然,如果我打印“%s”
我会得到“10m”
所以问题是,既然我是long的子类,为什么类在应该得到long值时调用\uu str\uu
顺便说一句,更多的测试表明%x
和%f
将打印整数值,这让我更加困惑。我还尝试添加\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
编辑#1,代码如下:
class Size(long):
'''Represents a size reflected bytes. Subclass of long.
Size passed in must be in the formats <int> or "0x<int>" or "0x<int><unit>" or "<int><unit>" or "<int><unit><int><unit>....".
"0x<int><unit>0x<int><unit>" or similar numbers are not supported as is "<int><unit><int>"
b = bytes
s = sectors (512-byte)
k = kilobytes
m = megabytes
g = gigabytes
t = terabytes
'''
units = { 'b':1, 's':512, 'k':1024, 'm':1024 ** 2, 'g':1024 ** 3, 't':1024 ** 4 }
def __new__(cls, value):
'''Creates a Size object with the specified value.
Value can be a number or a string (optionally prefixed with '0x' or
postfixed with a type character). If using hex, the final character
will be treated as part of the value if it is a hex digit, regardless
of whether it is a valid unit character.
Examples:
Size(50)
Size("0x100s") # 256 sectors
Size("64")
Size("512k")
Size("0x1b") # this is 1b bytes, not 1 byte
'''
self = _new_unit_number(value, cls.units, long, cls)
return self
def __init__(self, value):
self._orig_value = value
def __str__(self):
print "calling str"
return str(self._orig_value) # Convert to str in case the object was created w/an int
def __format__(self, format_spec):
print "calling format"
print format_spec
try:
value = format(str(self), format_spec)
except ValueError:
value = format(int(self), format_spec)
return value
def _new_unit_number(value, unit_list, num_type, cls):
'''Converts a string of numbers followed by a unit character to the
requested numeric type (int or long for example).
'''
base = 10
start = 0
digits = string.digits
try:
if value[0:2] == '0x':
start = 2
base = 16
digits = string.hexdigits
if value[-1] in digits:
return num_type.__new__(cls, value[start:], base)
else:
try:
# Use a regex to split the parts of the unit
regex_string = '(\d+[%s])' % (''.join(unit_list.keys()))
parts = [x for x in re.split(regex_string, value[start:]) if x]
if len(parts) == 1:
return num_type.__new__(cls, num_type(value[start:-1], base) * unit_list[value[-1]])
else:
# Total up each part
# There's probably a better way to do this.
# This converts each unit to its base type, stores it in total,
# only to be converted back to the base type.
total = 0
for part in parts:
total += num_type(part[start:-1], base) * unit_list[part[-1]]
# Finally return the requested unit
return num_type.__new__(cls, total)
except KeyError:
raise ValueError("Invalid %s unit identifier: %s"
% (cls.__name__, unit_list[value[-1]]))
# not a string or empty, see if we can still use the class's constructor
except (TypeError, IndexError):
return num_type.__new__(cls, value)
类大小(长):
''表示反映字节的大小。长的亚纲。
传入的大小的格式必须为“0x”或“0x”或“或”…”。
不支持“0x0x”或类似的数字
b=字节
s=扇区(512字节)
k=千字节
m=兆字节
g=千兆字节
t=TB
'''
单位={'b':1,'s':512,'k':1024,'m':1024**2,'g':1024**3,'t':1024**4}
定义新值(cls,值):
''创建具有指定值的大小对象。
值可以是数字或字符串(可选前缀为“0x”或
使用类型字符进行后期修复)。如果使用十六进制,则为最后一个字符
如果是十六进制数字,则将被视为值的一部分
是否为有效的单位字符。
示例:
尺寸(50)
大小(“0x100s”)#256个扇区
尺寸(“64”)
大小(“512k”)
大小(“0x1b”)#这是1b字节,而不是1字节
'''
self=\新的\单位\编号(值,cls.units,长,cls)
回归自我
定义初始值(自身,值):
自我。原始值=价值
定义(自我):
打印“调用str”
返回str(self._orig_value)#如果对象是使用int创建的,则转换为str
定义格式(自我,格式规格):
打印“调用格式”
打印格式规格
尝试:
值=格式(str(self),格式\规格)
除值错误外:
值=格式(int(self),格式\规格)
返回值
定义新单位编号(值、单位列表、数量类型、cls):
''将后跟单位字符的数字字符串转换为
请求的数字类型(例如int或long)。
'''
基数=10
开始=0
数字=字符串。数字
尝试:
如果值[0:2]=“0x”:
开始=2
基数=16
数字=字符串。十六进制数字
如果值[-1]为数字:
返回num_type.u_unew_u(cls,value[start:],base)
其他:
尝试:
#使用正则表达式拆分单元的各个部分
regex_string='(\d+[%s])'%('''.join(unit_list.keys()))
parts=[x代表re.split中的x(正则表达式字符串,值[start:]),如果x]
如果len(零件)==1:
返回num_type.\uu新建(cls,num_type(值[start:-1],base)*单位列表[value[-1]]))
其他:
#把每一部分加起来
#也许有更好的方法可以做到这一点。
#这会将每个单元转换为其基本类型,总共存储,
#仅转换回基本类型。
总数=0
对于部分中的部分:
总计+=数量类型(部件[开始:-1],基本)*单位列表[部件[-1]]
#最后返回请求的单元
返回数值类型。\uuuuu新建\uuuuuu(cls,总计)
除KeyError外:
提升值错误(“无效的%s单元标识符:%s”
%(cls.\uuuuu名称,单位列表[值[-1]]))
#不是字符串或空,看看我们是否仍然可以使用类的构造函数
除了(类型错误、索引器):
返回num\u type.\uuu new\uu(cls,值)
这不是一个真正的答案,但太长了,无法发表评论
我觉得这个问题非常有趣。我试图用以下方法复制这种行为:
#! /usr/bin/python2.7
class Size (long):
def __new__ (cls, arg):
if arg and type (arg) == str:
if arg [-1] == 'm':
return super (Size, cls).__new__ (cls, long (arg [:-1] ) * 2 ** 20)
return super (Size, cls).__new__ (cls, arg)
def __init__ (self, arg):
self.s = arg
def __str__ (self):
return self.s
a = Size ('12m')
print (a)
print ('%s' % a)
#The following fails horribly
print ('%d' % a)
OP.描述的行为。但现在有一个有趣的部分:当我从int继承而不是从long继承时,它工作得很顺利:
class Size (int):
def __new__ (cls, arg):
if arg and type (arg) == str:
if arg [-1] == 'm':
return super (Size, cls).__new__ (cls, int (arg [:-1] ) * 2 ** 20)
return super (Size, cls).__new__ (cls, arg)
def __init__ (self, arg):
self.s = arg
def __str__ (self):
return self.s
也就是说,它在python2中工作良好,但在python3中失败。奇怪,奇怪。请查看Python问题跟踪程序:
>一级(整数):
... 定义(自我):
... 返回“垃圾邮件”
...
>>>“%d”%I(42)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
SystemError:Objects/Unicode对象。c:13305:内部函数的参数错误
这在3.4.0alpha4中有效,但在3.[0123]中无效。如何定义大小
请注意,“m”是米的国际符号,或10^-3的前缀。如果您想要10^6,请使用M。如果您想要2^20,请使用Mi。在Python 2.7中,您从哪里获得printf()
函数?我假设您正在重写\uuuu new\uuu
?尝试实现int方法,但似乎忽略了它。还尝试了长时间的咯咯笑的方法。。。基本上你有我写过的类(我的类只支持更多的修饰符,比如K,m,g等等),这就是问题所在。有趣的是,它在long上失败,但在int上失败。。。。我需要很长时间,因为我们已经超出了int支持的32位。注意:代码在python2.7上工作(对于int
subclass)。它因long
子类而中断。
>>> class I(int):
... def __str__(self):
... return 'spam'
...
>>> '%d' % I(42)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
SystemError: Objects/unicodeobject.c:13305: bad argument to internal function