我在 Python 中有一個代碼:
class House:
def __init__(self, Address, Bedrooms, Bathrooms, Garage, Price):
self.Address= Address
self.Price = Price
self.Bathrooms= Bathrooms
self.Garage= Garage
if Garage == 1:
x="Attached garage"
else:
x="No Garage"
def getPrice(self):
return self.price
h1 = House("1313 Mockingbird Lane", 3, 2.5, True, 300000)
h2 = House("0001 Cemetery Lane", 4, 1.75, False, 400000)
現在,如果我鍵入,print(h1)我希望所有物件都顯示為多行字串。例如:
print(h1)給
1313 Mockingbird Lane
Bedrooms: 3 Bathrooms: 2.5
Attached garage
Price: 300000
uj5u.com熱心網友回復:
嘗試這個 :
class House:
def __init__(self, Address, Bedrooms, Bathrooms, Garage, Price):
self.Address= Address
self.Price = Price
self.Bathrooms= Bathrooms
self.Garage= Garage
if Garage == 1:
x="Attached garage"
else:
x="No Garage"
def __repr__(self):
return '\n'.join(f"{key} : {val}" for key, val in self.__dict__.items() if not key.startswith('_'))
def getPrice(self):
return self.price
h1 = House("1313 Mockingbird Lane", 3, 2.5, True, 300000)
h2 = House("0001 Cemetery Lane", 4, 1.75, False, 400000)
print(h1)
給你這個:
Address : 1313 Mockingbird Lane
Price : 300000
Bathrooms : 2.5
Garage : True
uj5u.com熱心網友回復:
您可以使用資料類從您的示例中洗掉大量“鍋爐板”代碼
from dataclasses import dataclass
@dataclass
class House:
Address: str
Bedrooms: int
Bathrooms: int
Garage: bool
Price: float
def __str__(self):
return f"""{self.Address}
Bedrooms: {self.Bedrooms} Bathrooms: {self.Bathrooms}
Garage: {self.Garage}
Price: {self.Price}"""
h1 = House("1313 Mockingbird Lane", 3, 2.5, True, 300000)
h2 = House("0001 Cemetery Lane", 4, 1.75, False, 400000)
print(h1)
print(h2)
dataclass 裝飾器會自動為你的類創建 init 函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/373227.html
