このサンプル シナリオを考慮します。
#!/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_str
custom_type
一方、それを変更すると、return super(custom_type, cls).new(value)
無限再帰になります。