To understand how these complex types (list
, dict
, set
, etc.) can be output as strings and thus printed, you first need to understand what custom types are and how you can override their __repr__()
method, which is in charge of the representation of the type and thus how it’s output as a string, when you print
it.
Let’s say you want to have a custom Point type with parameters x
, y
, and z
.
class Point:
def __init__(self, x, y, z):
self.x, self.y, self.z = x, y, z
pt = Point(0, 1, -1) # creates a new Point object, an instance of the Point class
print pt # <__main__.Point instance at 0x000000000000003F>
If you want a nicer print out, you can override the __repr__
method.
class Point:
def __init__(self, x, y, z):
self.x, self.y, self.z = x, y, z
def __repr__(self):
return "({}, {}, {})".format(self.x, self.y, self.z) # custom output
pt = Point(0, 1, -1)
print pt # (0, 1, -1)
As a beginner, this can be hard to understand, because you first need to get a grip on object oriented programming and classes.