0

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 
1
  • 1
    You have to implement a __str__(self) method in your class returning a multi-line string. Commented Dec 2, 2021 at 10:58

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, now I jus have to find a way to print "Attached garage" and "No garage"
0

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.

1 Comment

Thanks, I just added an if loop for the garage and now I'm all set to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.