You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: notebooks/beginner/classes.ipynb
+26Lines changed: 26 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -100,6 +100,32 @@
100
100
""
101
101
]
102
102
},
103
+
{
104
+
"cell_type": "markdown",
105
+
"metadata": {},
106
+
"source": [
107
+
"### `__str__()`\n",
108
+
"`__str__()` is a special method which is called when an instance of the class is converted to string (e.g. when you want to print the instance). In other words, by defining `__str__` method for your class, you can decide what's the printable version of the instances of your class. The method should return a string."
109
+
]
110
+
},
111
+
{
112
+
"cell_type": "code",
113
+
"execution_count": null,
114
+
"metadata": {},
115
+
"outputs": [],
116
+
"source": [
117
+
"class Person:\n",
118
+
" def __init__(self, name, age):\n",
119
+
" self.name = name\n",
120
+
" self.age = age\n",
121
+
"\n",
122
+
" def __str__(self):\n",
123
+
" return 'Person: {}'.format(self.name)\n",
124
+
"\n",
125
+
"jack = Person('Jack', 82)\n",
126
+
"print('This is the string presentation of jack: {}'.format(jack))"
<h2id="Class-variables-vs-instance-variables">Class variables vs instance variables<aclass="anchor-link" href="#Class-variables-vs-instance-variables">¶</a></h2><p>Class variables are shared between all the instances of that class whereas instance variables can hold different values between different instances of that class.</p>
12003
+
<h3id="__str__()"><code>__str__()</code><aclass="anchor-link" href="#__str__()">¶</a></h3><p><code>__str__()</code> is a special method which is called when an instance of the class is converted to string (e.g. when you want to print the instance). In other words, by defining <code>__str__</code> method for your class, you can decide what's the printable version of the instances of your class. The method should return a string.</p>
<spanclass="nb">print</span><spanclass="p">(</span><spanclass="s1">'This is the string presentation of jack: </span><spanclass="si">{}</span><spanclass="s1">'</span><spanclass="o">.</span><spanclass="n">format</span><spanclass="p">(</span><spanclass="n">jack</span><spanclass="p">))</span>
<h2id="Class-variables-vs-instance-variables">Class variables vs instance variables<aclass="anchor-link" href="#Class-variables-vs-instance-variables">¶</a></h2><p>Class variables are shared between all the instances of that class whereas instance variables can hold different values between different instances of that class.</p>
0 commit comments