2

変数 self.list を含む "Set" クラスを作成し、__repr__and__str__メソッドを記述してオブジェクトを出力および str() できるようにする必要があります。2 番目のファイル (driver1.py) である「ドライバー ファイル」は Set オブジェクトを作成し、print(str(set_object)) と print(set_object) を呼び出そうとしますが、どちらの呼び出しもメモリ アドレスSet.Set instance at 0x1033d1488>またはその他の場所のみを出力します。これを変更するにはどうすればよいですか?set_object の内容をフォームに出力したい{1,2,3}

インデントを更新した後のコード全体を次に示します。

クラスセット:

def __init__(self):
    self.list = []

def add_element(self, integer):
    if integer not in self.list:
        self.list.append(integer)

def remove_element(self, integer):
    while integer in self.list: self.list.remove(integer)

def remove_all(self):
    self.list = []

def has_element(self, x):
    while x in self.list: return True
    return False
#probably doesnt work, __repr__
def __repr__(self):
    if self.list.len == 0:
        return "{}"
    return "{"+", ".join(str(e) for e in self.list) +"}"
#Same as above, probably doesnt work
def __str__(self):
    if len(self.list) == 0:
        return "{}"
    return "{"+", ".join(str(e) for e in self.list) +"}"

def __add__(self, other):
    counter = 0
    while counter <= len(other.list):
        if other.list[counter] not in self.list:
            self.list.append(other.list[counter])
        counter = counter + 1

エラーが表示されるのはなぜですか:

 Traceback (most recent call last):
  File "driver1.py", line 1, in <module>
    from Set import *
  File "/Users/josh/Documents/Set.py", line 23
    return "{"+", ".join(str(e) for e in self.list) +"}"
                                                       ^
IndentationError: unindent does not match any outer indentation level
4

2 に答える 2

2

タブとスペースが混在しています。そうしないでください。するとこうなります。Python は、いくつかのメソッドが実際には他のいくつかのメソッドの内部にあると考えているため、クラスには実際にはorメソッドSetがありません。__str____repr__

インデントを修正すると、問題は解決します。今後このような問題を回避するには、エディターで「空白を表示」を有効にし、-ttタブ関連のバグが発生していると思われる場合は、コマンド ライン オプションを使用して Python を実行してみてください。

于 2014-09-14T22:36:49.860 に答える
1

別の問題があります:

if self.list.len == 0:

あなたはおそらくそうするつもりでした:

if len(self.list) == 0:

この問題が修正されると、コードは次のように機能します。

s = Set()
s.add_element(1)
s.add_element(1)
s.add_element(2)
s.add_element(3)
print s  # prints {1, 2, 3}
于 2014-09-14T22:42:14.087 に答える