2016-04-15 22 views
0

私は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 

答えて

3

int機能は、ユーザー定義クラスに対処することはできません。 __int__(initではない)関数は、組み込みのPython int()に、ユーザ定義クラス(この場合はバイナリ)をintに変換する方法に関する関数情報を与えます。

class Binary: 
    ...your init here 
    def __int__(self): 
     return int(self.value) #assuming self.value is of type int 

あなたは次のようなことができるはずです。

print int(Binary(0x3)) #should print 3 

は、私はまた、__init__関数の入力とself.valueの値を標準化提案するかもしれません。現在のところ、文字列(例:'0b011'または0x3)またはintを受け入れることができます。なぜなら、常に文字列を入力として受け入れ、常にself.valueをintとして保持するのではないのです。

+0

こんにちはギャレット、お返事ありがとうございます。私は初心者なので、理解できないのは残念です。私はhttps://docs.python.org/2/library/functions.html#intを読んだ。 1.「int関数は、クラス内でどのように動作するべきかを指定しない限り、ユーザー定義のクラスを扱うことができません。私が誤解していない限り、ブログ作成者が開発したクラスはこれをしません(上記の編集をご覧ください)。 2.「なぜ文字列を入力として受け入れるのはなぜではないのですか?」 - どうやってこれを行うのですか? – user61629

+0

編集内容を確認してください。 –

+0

こんにちは、ありがとうございます。 2つの質問:1)は、組み込みのint()をオーバーライドするバイナリクラスの '__int__'関数です。2.「なぜ文字列を入力として受け入れるのはなぜですか?」 - どうやってこれを行いますか? – user61629

関連する問題