This forum is now read-only. Please use our new forums at discuss.codecademy.com.
Can someone explain what __repr__() does a little more thoroughly please?
It's not clear from the practice program
When we create new types by defining classes, we can take advantage of certain features of Python to make the new classes convenient to use. One of these features is "special methods", also referred to as "magic methods".
Special methods have names that begin and end with two underscores. We define them, but do not usually call them directly by name. Instead, they execute automatically under under specific circumstances.
It is convenient to be able to output the value of an instance of an object by using a
__repr__ special method can be used to arrange for this to happen. If we define this method, it can get called automatically when we
__str__ special method, used for a similar, but not identical purpose, that may get precedence, if we have also defined it.
If we have not defined, the
__repr__ method for the
Point3D class, and have instantiated
my_point as an instance of
Point3D, and then we do this ...
... we may see this as the output ...
<Point3D object at 0x7fc14c4848d0>
Not very nice, eh?
So, we define the
__str__ special method, or both, to get better output.
Going beyond the instructions for Exercise 11: Building useful classes, a little, try this ...
class Point3D(object): def __init__(self,a,b,c): self.x = a self.y = b self.z = c def __repr__(self): return "Point3D(%d, %d, %d)" % (self.x, self.y, self.z) def __str__(self): return "(%d, %d, %d)" % (self.x, self.y, self.z) my_point = Point3D(1, 2, 3) print `my_point` # __repr__ gets called automatically print my_point # __str__ gets called automatically
Point3D(1, 2, 3) (1, 2, 3)
The ` character is often referred to as a backquote. When an expression is enclosed in backquotes,
__repr__ is called for the appropriate type to represent the resulting object, when you
__str__ will take precedence over
__repr__ to represent the object as a
str. If the type of the resultant object inherits from
__repr__ has not been overridden for that type, the object will be represented in a manner similar to this, when you use backquotes ...
<__builtin__.Point3D instance at 0x7f6511c883b0>
Note that the name of the class is part of the output, along with some hexadecimal gibberish. You can experiment further to find out what happens under various circumstances.
In any case, it is a good idea to write
__str__ methods, when defining a class, so that instances of the class are represented in a more useful manner than the default.
The explanation above helped a lot to understand the str and repr .But could someone please explain the difference between the 2 print statements.
print `my_point` # __repr__ gets called automatically print my_point # __str__ gets called automatically
Does `` overrides the precedence of str() over repr()?