0

このサンプル シナリオを考慮します。

#!/usr/bin/python
import binascii
import cProfile
import re

class custom_str(str):
    __strip_non_hex = re.compile(r'^[^:]+:|[^0-9A-Fa-f]')

    def __new__(cls, value):
        return super(custom_str, cls).__new__(cls, value)

    @classmethod
    def new(cls, value):
        # creates a pure-hexadecimal string
        return cls(re.sub(cls.__strip_non_hex, '', value))

class custom_type(custom_str):
    def __new__(cls, value):
        # here I've to use custom_str.new()
        return super(custom_type, cls).__new__(cls, custom_str.new(value))

    @classmethod
    def new(cls, value):
        return cls('hex:%s' % (binascii.hexlify(value)))

if __name__ == '__main__':
    # tests
    v = custom_str('666f6f')
    assert v == '666f6f'
    assert type(v) == custom_str
    v = custom_str.new('66,6f,6f')
    assert v == '666f6f'
    assert type(v) == custom_str
    v = custom_type('hex:66,6f,6f')
    assert v == '666f6f'
    assert type(v) == custom_type
    v = custom_type.new('foo')
    assert v == '666f6f'
    assert type(v) == custom_type
    # profiling
    cProfile.run("custom_type.new('foo')", sort='call')

コードは機能し、テストはパスします。custom_str.__new__()二度電話を避けることができるかどうか疑問に思っています。

に変更custom_type.__new__()すると動作しますが、 の代わりにreturn custom_str.new(value)タイプになります。custom_strcustom_type

一方、それを変更すると、return super(custom_type, cls).new(value)無限再帰になります。

4

1 に答える 1

1
_strip_non_hex = re.compile(r'^[^:]+:|[^0-9A-Fa-f]')

def _strip(string):
    return re.sub(_strip_non_hex, '', value)

class custom_str(str):
    @classmethod
    def new(cls, value):
        # creates a pure-hexadecimal string
        return custom_str.__new__(cls, _strip(value))

class custom_type(custom_str):
    def __new__(cls, value):
        return super(custom_type, cls).__new__(cls, _strip(value))

    @classmethod
    def new(cls, value):
        return cls('hex:%s' % (binascii.hexlify(value)))

非 16 進ストリッピング ロジックをnew独自の関数から引き出して、依存関係グラフを解きほぐします。

于 2013-09-05T22:47:30.927 に答える