I have a code in 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)
now if I type print(h1)
I want all the object to be shown as a multi-lined string. For Example:
print(h1)
gives
1313 Mockingbird Lane
Bedrooms: 3 Bathrooms: 2.5
Attached garage
Price: 300000
CodePudding user response:
Try this :
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)
Gives you this :
Address : 1313 Mockingbird Lane
Price : 300000
Bathrooms : 2.5
Garage : True
CodePudding user response:
You can remove a lot of the 'boiler plate' code from your example by using dataclasses
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)
The dataclass decorator will automatically create the init function for your class.