__str__, __repr__は特殊メソッドと呼ぶ
initのみの場合
class Person: def __init__(self, name: str, age: int) -> None: self.name = name self.age = age mike = Person('Mike', 20) print(mike)
class Person: def __init__(self, name: str, age: int) -> None: self.name = name self.age = age mike = Person('Mike', 20) print(f'name: {mike.name}, age: {mike.age}')
classの中に書く
class Person: def __init__(self, name: str, age: int) -> None: self.name = name self.age = age def __str__(self) -> str: return f'name: {mike.name}, age: {mike.age}' mike = Person('Mike', 20) print(mike)
__repr__ は同じ値のオブジェクトを再生成できる文字列を定義。
class Person: def __init__(self, name: str, age: int) -> None: self.name = name self.age = age def __repr__(self) -> str: return f'name: {mike.name}, age: {mike.age}' mike = Person('Mike', 20) print(repr(mike))
class Person: def __init__(self, name: str, age: int) -> None: self.name = name self.age = age def __repr__(self) -> str: return f'name: {mike.name}, age: {mike.age}' mike = Person('Mike', 20) print(repr(mike))