ROOT
6.16/01
Reference Guide
tutorials
pyroot
pyroot003_prettyPrinting.py
Go to the documentation of this file.
1
## \file
2
## \ingroup tutorial_pyroot
3
## \notebook -nodraw
4
## This tutorial illustrates the pretty printing feature of PyROOT, which reveals
5
## the content of the object if a string representation is requested, e.g., by
6
## Python's print statement. The printing behaves similar to the ROOT prompt
7
## powered by the C++ interpreter cling.
8
##
9
## \macro_code
10
##
11
## \date June 2018
12
## \author Stefan Wunsch, Enric Tejedor
13
14
import
ROOT
15
16
# Create an object with PyROOT
17
obj = ROOT.std.vector(
"int"
)(3)
18
for
i
in
range(obj.size()):
19
obj[i] = i
20
21
# Print the object, which reveals the content. Note that `print` calls the special
22
# method `__str__` of the object internally.
23
print(obj)
24
25
# The output can be retrieved as string by any function that triggers the `__str__`
26
# special method of the object, e.g., `str` or `format`.
27
print(str(obj))
28
print(
"{}"
.format(obj))
29
30
# Note that the interactive Python prompt does not call `__str__`, it calls
31
# `__repr__`, which implements a formal and unique string representation of
32
# the object.
33
print(repr(obj))
34
obj
35
36
# The print output behaves similar to the ROOT prompt, e.g., here for a ROOT histogram.
37
hist = ROOT.TH1F(
"name"
,
"title"
, 10, 0, 1)
38
print(hist)
39
40
# If cling cannot produce any nice representation for the class, we fall back to a
41
# "<ClassName at address>" format, which is what `__repr__` returns
42
ROOT.gInterpreter.Declare(
'class MyClass {};'
)
43
m = ROOT.MyClass()
44
print(m)
45
print(str(m) == repr(m))
46