3

我已经开始在 Python27 中为类型化数组编写一个模块。到现在为止还挺好; 但我停了下来。我注意到python中的Long类型只有4个字节,但在64位处理器上应该是8个字节。我可以指定吗?

有什么办法可以清理我的__new__(self)方法吗?我试图覆盖超级构造函数:__init__(self, typecode[, initializer]),但我不允许我更改参数。

例如,以下代码不起作用:

class TypedIntegerArray(array):
    def __init__(self, type, size):
        array.__init__(self, type, (0 for i in range(0,size)))

我想setup()在数组上运行一个方法,将所有逻辑放入__new__(self),但__new__()发生在对象创建之前,所以我必须创建一个临时对象以在返回它之前从中获取属性。

模块

#!/usr/bin/env python

# Typecode       Type        Min bytes
#    'c'        character         1
#    'b'     signed integer       1
#    'B'    unsigned integer      1
#    'h'     signed integer       2
#    'H'    unsigned integer      2
#    'i'     signed integer       2
#    'I'    unsigned integer      2
#    'l'     signed integer       4
#    'L'    unsigned integer      4
#    'f'     floating point       4
#    'd'     floating point       8

from array import array
from math import floor, log10
from sys import getsizeof, maxsize

class TypedIntegerArray(array):
    def __new__(self, type, size):
        arr = array.__new__(self, type, (0 for i in range(0,size)))
        exp = 1 if arr.typecode.islower() else 0
        self.mask = int('FF'*arr.itemsize, 16)
        self.frmt = '{0:0' + str(arr.itemsize * 8) + 'b}'
        self._maxValue = 2 ** (arr.numBits() - exp) - 1
        self._minValue = -1 * (self._maxValue + 1) if exp == 1 else 0
        return arr
    def size(self):
        return len(self)
    def numBits(self):
        return self.itemsize * 8
    def intToBin(self, value):
        value = (value + self.mask) + 1 if value < 0 else value
        return self.frmt.format(value)
    def maxValue(self):
        return self._maxValue
    def minValue(self):
        return self._minValue
    def magnitude(self):
        return int(floor(log10(self.size()-1) + 1))
    def getRange(self):
        return 'Range[{:d}, {:d}]'.format(\
            self.minValue(), self.maxValue())
    def disp(self, binary=False):
        type = 's' if binary else 'd'
        frmt = '{:0' + str(self.magnitude()) + 'd}. {:' + type + '}'
        i = 0 
        for item in self.tolist():
            value = self.intToBin(item) if binary else item
            print(frmt.format(i, value))
            i+=1
    def __repr__(self):
        return '{:s}[{:d}]'.format(self.__class__.__name__, self.size())

class ByteArray(TypedIntegerArray):
    def __new__(self, size):
        return TypedIntegerArray.__new__(self, 'b', size)
class UByteArray(TypedIntegerArray):
    def __new__(self, size):
        return TypedIntegerArray.__new__(self, 'B', size)
class IntegerArray(TypedIntegerArray):
    def __new__(self, size):
        return TypedIntegerArray.__new__(self, 'h', size)
class UIntegerArray(TypedIntegerArray):
    def __new__(self, size):
        return TypedIntegerArray.__new__(self, 'H', size)
class LongArray(TypedIntegerArray):
    def __new__(self, size):
        return TypedIntegerArray.__new__(self, 'l', size)
class ULongArray(TypedIntegerArray):
    def __new__(self, size):
        return TypedIntegerArray.__new__(self, 'L', size)

if __name__ == '__main__':
    # Create 1 of each type of array
    byteArr = ByteArray(8)
    ubyteArr = UByteArray(8)
    intArr = IntegerArray(16)
    uintArr = UIntegerArray(16)
    longArr = LongArray(32)
    ulongArr = ULongArray(32)

    # Specify a format for the ranges
    frmt = '{:17s} {:s}'

    # Print each of the ranges
    print frmt.format(byteArr, byteArr.getRange())
    print frmt.format(ubyteArr, ubyteArr.getRange())
    print frmt.format(intArr, intArr.getRange())
    print frmt.format(uintArr, uintArr.getRange())
    print frmt.format(longArr, longArr.getRange())
    print frmt.format(ulongArr, ulongArr.getRange())

    # Test array mutation and display
    for i in range(byteArr.size()):
        byteArr[i] = byteArr.maxValue() if i % 2 == 0 else byteArr.minValue()
    byteArr.disp(True)

输出

ByteArray[8]      Range[-128, 127]
UByteArray[8]     Range[0, 255]
IntegerArray[16]  Range[-32768, 32767]
UIntegerArray[16] Range[0, 65535]
LongArray[32]     Range[-2147483648, 2147483647]
ULongArray[32]    Range[0, 4294967295]
0. 01111111
1. 10000000
2. 01111111
3. 10000000
4. 01111111
5. 10000000
6. 01111111
7. 10000000
4

1 回答 1

2

我认为您实际上要做的是自定义类型化数组类的创建。类似numBitsormaxValue的东西是类型的属性,而不是单个实例的属性,因此应该是类属性。实际上,在您当前的实现中,它们是类属性:__new__只要创建实例,它们就会在方法中设置。请记住,第一个参数__new__实际上是类,而不是实例。它经常被称为cls而不是self为了明确这一点。

类创建的定制通常使用元类来完成。调用元类的__new__方法来创建实际的类。新类的所有类属性都可以在这里设置:

from array import array

class TypedArrayMeta(type):
    def __new__(metacls, name, bases, dct):
        if "typecode" in dct:
            typecode = dct["typecode"]
            dct["num_bits"] = 8 * array(typecode).itemsize
            dct["is_signed"] = typecode.islower()
            # any other class attributes go into dct
        return type.__new__(metacls, name, bases, dct)

class TypedArray(array):
    __metaclass__ = TypedArrayMeta
    # other methods go here

然后,您可以轻松定义所有自定义类型数组类:

class ByteArray(TypedArray): typecode = "b" 
class UByteArray(TypedArray): typecode = "B" 
class IntegerArray(TypedArray): typecode = "h"
class UIntegerArray(TypedArray): typecode = "H"
class LongArray(TypedArray): typecode = "l"
class ULongArray(TypedArray): typecode = "L"

即使在创建实例之前,类属性现在也已正确设置:

print(ByteArray.num_bits, ByteArray.is_signed)
print(UByteArray.num_bits, UByteArray.is_signed)
print(IntegerArray.num_bits, IntegerArray.is_signed)
print(UIntegerArray.num_bits, UIntegerArray.is_signed)
print(LongArray.num_bits, LongArray.is_signed)
print(ULongArray.num_bits, ULongArray.is_signed)

至于你的第一个问题,在我的 64 位 Linux 上,“L”类型实际上是 8 个字节。

于 2013-12-18T16:55:53.590 回答