user2077968
user2077968

Reputation: 5

Python Returns on calling class object

I'm making a class in Python called House. It has instance variables such as street name and and street number.

h = House(1234, "main street")
>>>h.street_name
Main Street
>>>h.street_number
1234

>>>h
<__main__.House object at 0x27ffbd0>

when you call "h", the program is supposed to return "1234 Main Street" instead. How should I approach this problem?

Upvotes: 0

Views: 313

Answers (2)

David Robinson
David Robinson

Reputation: 78590

You want to define a __str__ method that returns a string representation. For example:

class House:
    # other methods
    def __str__(self):
        return "%d %s" % (self.street_number, self.street_name)

Upvotes: 4

eyquem
eyquem

Reputation: 27565

....a class in Python called House. It has instance variables....

A class doesn't have instance variables. The instance has

.

'variable' is a confusing word in Python.
Python doesn't offer "variables" (= boxes) to the developper, only objects.
What people confusingly call 'variables' are most of the time the identifiers (= names).... or maybe ... what... I don't know and they don't know themselves, because there are no variables at the use of the developper in Python....

.

You can't call h if it isn't a callable object (a class, a function....)

What you name 'call' is simply the demand to Python to present you the object h. As it isn't a simple object as is an integer or a string, but an instance, that is to say an object whith attributes that are data attributes and methods, Python doesn't present you extensively the instance with all its attributes and the values of the attributes (it may be long for certain instances), it presents you a short description of the instance, saying which class it is an instance of, and giving its address.

Upvotes: 0

Related Questions