0

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?

2
  • 3
    The Python command prompt isn't "calling" the object, it's calling the object's __repr__() method which is suppose to return a string representing the value of the object. If the object doesn't have a __repr__() method, but does have a __str__() method, it will use that instead. What you're seeing for a class without either is what the default method returns. Commented Feb 17, 2013 at 2:12
  • When you say "call h", do you mean h()? Commented Feb 17, 2013 at 5:20

2 Answers 2

4

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

1 Comment

__repr__ should return valid Python expression that reconstructs the object if possible. __str__ is for converting to string.
0

....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.

Comments

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.