2017-12-16 14 views
0

私はちょうどJavaの最初の学期を終え、私たちのプロジェクトの一部をPythonコードに変換しようとしています。私たちは、名前(str)、年齢(double)、および重み(double)を持つ必要があるPetRecordクラスを持っています。プロジェクトでは、これらすべてのgetterとsetter、およびtoStringを作成する必要がありました。python3クラスの__str__の出力文字列のフォーマット

私は、print(object_name)でスクリーンに印刷されるpythonオブジェクトの属性を可能にする__str__メソッドの使用例を見つけました。なぜ私の書式が正しく動作していないのか分かりません。誰かがそれを投げている理由に私を啓発することができた場合:

Traceback (most recent call last): 
    File "PetRecord.py", line 92, in <module> 
    print(TestPet) 
    File "PetRecord.py", line 49, in __str__ 
    return('Name: {self.__name} \nAge: {self.__age} \nWeight:{self.__weight}').format(**self.__dict__) # this is printing literally 
KeyError: 'self' 

をコード自体(この記事のためのビットのフォーマットの行を変更):

class PetRecord(object): 
    ''' 
    All pets come with names, age and weight 
    ''' 
    def __init__(self, name='No Name', age=-1.0, 
       weight=-1.0): 
    # data fields 
    self.__name = name 
    self.__age = age 
    self.__weight = weight 

    def __str__(self): 
    # toString() 
    return('Name: {self.__name} \nAge: {self.__age} 
      \nWeight:{self.__weight}').format(
      **self.__dict__) # this is printing literally 

すべてで任意の助けいただければ幸いです。

答えて

0

KeyErrorの理由は、selfがフォーマット文字列に渡されないためです。あなたはしかし、別の問題を抱えている

- シングルインスタンスを付加は、2つのアンダースコア(「プライベート」それらを作る)と属性名を - the actual names would be mangled - これは、例えば、あなたがself._PetRecord__nameとして__nameにアクセスする必要があるだろう、ということを意味します

Pythonの3.6以降では、あなたが f-stringsを利用することができることを
def __str__(self): 
    return "Name: {self._PetRecord__name}\nAge: {self._PetRecord__age}\nWeight: {self._PetRecord__weight}".format(self=self) 

注:

def __str__(self): 
    return f"Name: {self._PetRecord__name}\nAge: {self._PetRecord__age}\nWeight: {self._PetRecord__weight}" 
+0

ありがとうございました!これはまさに私が探していたものです。 – user8642594

関連する問題