私はhttp://blog.thedigitalcatonline.com/blog/2015/05/13/python-oop-tdd-example-part1/#.VxEEfjE2sdQで作業しています。私はこれを繰り返し実行しています。私は含めて、pytestを使用してテストスイートを通じて実行しているよTypeError:int()引数は 'Binary'ではなく文字列または数値でなければなりません
class Binary:
def __init__(self,value):
self.value = str(value)
if self.value[:2] == '0b':
print('a binary!')
self.value= int(self.value, base=2)
elif self.value[:2] == '0x':
print('a hex!')
self.value= int(self.value, base=5)
else:
print(self.value)
return None
:
def test_binary_init_hex():
binary = Binary(0x6)
assert int(binary) == 6
E TypeError: int() argument must be a string or a number, not 'Binary'
def test_binary_init_binstr():
binary = Binary('0b110')
assert int(binary) == 6
E TypeError: int() argument must be a string or a number, not 'Binary'
私はこのエラーを理解していないこの時点で私は、次のバイナリクラスを持っています。私は間違って何をしていますか?
編集:HERESにブログの著者によって生成クラス:あなたはそれがどのように動作するかをクラスに指定しない限り
import collections
class Binary:
def __init__(self, value=0):
if isinstance(value, collections.Sequence):
if len(value) > 2 and value[0:2] == '0b':
self._value = int(value, base=2)
elif len(value) > 2 and value[0:2] == '0x':
self._value = int(value, base=16)
else:
self._value = int(''.join([str(i) for i in value]), base=2)
else:
try:
self._value = int(value)
if self._value < 0:
raise ValueError("Binary cannot accept negative numbers. Use SizedBinary instead")
except ValueError:
raise ValueError("Cannot convert value {} to Binary".format(value))
def __int__(self):
return self._value
こんにちはギャレット、お返事ありがとうございます。私は初心者なので、理解できないのは残念です。私はhttps://docs.python.org/2/library/functions.html#intを読んだ。 1.「int関数は、クラス内でどのように動作するべきかを指定しない限り、ユーザー定義のクラスを扱うことができません。私が誤解していない限り、ブログ作成者が開発したクラスはこれをしません(上記の編集をご覧ください)。 2.「なぜ文字列を入力として受け入れるのはなぜではないのですか?」 - どうやってこれを行うのですか? – user61629
編集内容を確認してください。 –
こんにちは、ありがとうございます。 2つの質問:1)は、組み込みのint()をオーバーライドするバイナリクラスの '__int__'関数です。2.「なぜ文字列を入力として受け入れるのはなぜですか?」 - どうやってこれを行いますか? – user61629