-5

I wrote this class:

class Dinosaurus:

    def __init__(self, nimi, suurus, värv, toit):
        self.nimi = nimi
        self.suurus = suurus
        self.värv = värv
        self.toit = toit

But when I try to use it ...

Dinosaur = Dinosaurus ("Stegosaurus", "20", "sinine", "Liha")

print(Dinosaur)

I'm getting an error:

<__main__.Dinosaurus object at 0x026B5210>

What am I doing wrong?

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
Remqop
  • 1
  • 3
    That is not an error. – juanpa.arrivillaga Nov 11 '18 at 11:40
  • Check the possible duplicate link provided by @juanpa.arrivillaga. If you want a human readable string for print, you need to tell Python how to do so by implementing a `__str` method on your class. – Alex Nov 11 '18 at 11:49
  • That's not a duplicate. The linked question asks how to alter the representation of an object, whereas this one is based on the misapprehension that its representation is some kind of error. – Zero Piraeus Nov 11 '18 at 12:11

1 Answers1

4

<__main__.Dinosaurus object at 0x026B5210> is not an error – it's the representation of your object.

A little experimentation shows that Dinosaur has all the attributes you assigned it:

>>> Dinosaur = Dinosaurus ("Stegosaurus", "20", "sinine", "Liha")
>>> Dinosaur
<__main__.Dinosaurus object at 0x7f893d9b5320>
>>> Dinosaur.nimi
'Stegosaurus'
>>> Dinosaur.suurus
'20'
>>> Dinosaur.värv
'sinine'
>>> Dinosaur.toit
'Liha'

If you want to change the representation that gets shown when you print instances of your class, you need to write a special __repr__ method to tell Python how they should be represented, for example:

class Dinosaurus:

    def __init__(self, nimi, suurus, värv, toit):
        self.nimi = nimi
        self.suurus = suurus
        self.värv = värv
        self.toit = toit

    def __repr__(self):
        return 'Dinosaurus(%r, %r, %r, %r)' % (self.nimi, self.suurus, self.värv, self.toit)

>>> Dinosaur = Dinosaurus ("Stegosaurus", "20", "sinine", "Liha")
>>> print(Dinosaur)
Dinosaurus('Stegosaurus', '20', 'sinine', 'Liha')

There's also a __str__ method you can define, which Python will use in preference to __repr__ when printing objects if both are defined. You should think of __str__ as returning an informal, human-friendly representation of an object, and __repr__ as the formal representation (which, if possible, should be a valid Python expression that could be used to make an exact copy of it, as in my example above).

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160