{"id":6027,"date":"2022-05-06T23:14:07","date_gmt":"2022-05-06T21:14:07","guid":{"rendered":"http:\/\/miro.borodziuk.eu\/?p=6027"},"modified":"2026-01-23T13:53:12","modified_gmt":"2026-01-23T12:53:12","slug":"object-oriented-programming-in-python","status":"publish","type":"post","link":"http:\/\/miro.borodziuk.eu\/index.php\/2022\/05\/06\/object-oriented-programming-in-python\/","title":{"rendered":"Object-Oriented Programming in Python"},"content":{"rendered":"<p>1. A <b>class<\/b> is an idea (more or less abstract) which can be used to create a number of incarnations \u2013 such an incarnation is called an <b>object<\/b>.<\/p>\n<p><!--more--><\/p>\n<p>2. When a class is derived from another class, their relation is named <b>inheritance<\/b>. The class which derives from the other class is named a <b>subclass<\/b>. The second side of this relation is named <b>superclass<\/b>. A way to present such a relation is an <b>inheritance diagram<\/b>, where:<\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>superclasses are always presented <b>above<\/b> their subclasses;<\/li>\n<li>relations between classes are shown as arrows directed <b>from the subclass toward its superclass<\/b>.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-6031\" src=\"http:\/\/miro.borodziuk.eu\/wp-content\/uploads\/OOP.jpg\" alt=\"\" width=\"882\" height=\"501\" srcset=\"http:\/\/miro.borodziuk.eu\/wp-content\/uploads\/OOP.jpg 882w, http:\/\/miro.borodziuk.eu\/wp-content\/uploads\/OOP-300x170.jpg 300w, http:\/\/miro.borodziuk.eu\/wp-content\/uploads\/OOP-768x436.jpg 768w\" sizes=\"(max-width: 767px) 89vw, (max-width: 1000px) 54vw, (max-width: 1071px) 543px, 580px\" \/><\/p>\n<p>&nbsp;<\/p>\n<p>3. Objects are equipped with:<\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>a <b>name<\/b> which identifies them and allows us to distinguish between them;<\/li>\n<li>a set of <b>properties<\/b> (the set can be empty)<\/li>\n<li>a set of <b>methods<\/b> (can be empty, too)<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<p>4. To define a Python class, you need to use the <code>class<\/code> keyword. For example:<\/p>\n<pre class=\"lang:default decode:true\">class This_Is_A_Class:\r\n     pass\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>5. To create an object of the previously defined class, you need to use the class as if it were a function. For example:<\/p>\n<pre class=\"lang:default decode:true \">this_is_an_object = This_Is_A_Class()<\/pre>\n<p>&nbsp;<\/p>\n<p>6. A <b>stack<\/b> is an object designed to store data using the <b>LIFO<\/b> model. It&#8217;s an abbreviation for a very clear description of the stack&#8217;s behavior: <strong>Last In &#8211; First Out<\/strong>. The coin that came last onto the stack will leave first. The stack usually performs at least two operations, named<\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li><code><strong>push <\/strong><\/code>(when a new element is put on the top)<\/li>\n<li><strong><code> pop <\/code><\/strong>(when an existing element is taken away from the top).<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-6034 size-full\" src=\"http:\/\/miro.borodziuk.eu\/wp-content\/uploads\/Stack.jpg\" alt=\"\" width=\"672\" height=\"584\" srcset=\"http:\/\/miro.borodziuk.eu\/wp-content\/uploads\/Stack.jpg 672w, http:\/\/miro.borodziuk.eu\/wp-content\/uploads\/Stack-300x261.jpg 300w\" sizes=\"(max-width: 672px) 100vw, 672px\" \/><\/p>\n<p>The stack &#8211; the procedural approach<\/p>\n<pre class=\"lang:default decode:true\">stack = []\r\n\r\ndef push(val):\r\n    stack.append(val)\r\n\r\ndef pop():\r\n    val = stack[-1]\r\n    del stack[-1]\r\n    return val\r\n\r\npush(3)\r\npush(2)\r\npush(1)\r\n\r\nprint(pop())\r\nprint(pop())\r\nprint(pop())<\/pre>\n<p><code>1<\/code><\/p>\n<p><code>2<\/code><\/p>\n<p><code>3<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>7. Implementing the stack in a procedural model raises several problems which can be solved by the techniques offered by <b>OOP<\/b> (<b>O<\/b>bject <b>O<\/b>riented <b>P<\/b>rogramming):<\/p>\n<p>&nbsp;<\/p>\n<p>8. The part of the Python class responsible for creating new objects is called the <b>constructor.<\/b><\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>the constructor&#8217;s name is always<strong><code> __init__<\/code><\/strong>;<\/li>\n<li>it has to have <strong>at least one parameter<\/strong>; the parameter is used to represent the newly created object &#8211; you can use the parameter to manipulate the object, and to enrich it with the needed properties; you&#8217;ll make use of this soon;<\/li>\n<li>the obligatory parameter is usually named <strong><code>self<\/code> <\/strong>&#8211; it&#8217;s only a convention, but you should follow it &#8211; it simplifies the process of reading and understanding your code.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true\">class Stack:  # Defining the Stack class.\r\n    def __init__(self):  # Defining the constructor function.\r\n        print(\"Hi!\")\r\n\r\n\r\nstack_object = Stack()  # Instantiating the object.<\/pre>\n<p>&nbsp;<\/p>\n<p>9. To create a <strong>property<\/strong> inside a class it is used a<strong> dot notation<\/strong>, just like when invoking methods; this is the general convention for accessing an object&#8217;s properties \u000f you need to name the object, put a dot (.) after it, and specify the desired property&#8217;s name;<\/p>\n<pre class=\"lang:default decode:true\">class Stack:\r\n    def __init__(self):\r\n        self.stack_list = []\r\n\r\nstack_object = Stack()\r\nprint(len(stack_object.stack_list))\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>10. If we want to hide any of a class&#8217;s components from the outside world, we should start its name with <code><strong>__<\/strong><\/code>. Such components are called <b>private<\/b>.<\/p>\n<p>The ability to hide (protect) selected values against unauthorized access is called <strong>encapsulation<\/strong>; the encapsulated values can be neither accessed nor modified if you want to use them exclusively;<\/p>\n<pre class=\"lang:default decode:true\">class Stack:\r\n    def __init__(self):\r\n        self.__stack_list = []\r\n\r\nstack_object = Stack()\r\nprint(len(stack_object.__stack_list))<\/pre>\n<p><code>Traceback (most recent call last):<\/code><\/p>\n<p><code>File \"main.py\", line 7, in &lt;module&gt;<\/code><\/p>\n<p><code>print(len(stack_object.__stack_list))<\/code><\/p>\n<p><code>AttributeError: 'Stack' object has no attribute '__stack_list'<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>11. A class <b>method<\/b> is actually a function declared inside the class and able to access all the class&#8217;s components. Each class method declaration must contain at least one parameter (always the first one) usually referred to as <strong><code>self<\/code><\/strong>, and is used by the objects to identify themselves.<\/p>\n<pre class=\"lang:default decode:true\">class Stack:\r\n    def __init__(self):\r\n        self.__stack_list = []\r\n\r\n    def push(self, val):\r\n        self.__stack_list.append(val)\r\n\r\n    def pop(self):\r\n        val = self.__stack_list[-1]\r\n        del self.__stack_list[-1]\r\n        return val\r\n\r\nstack_object = Stack()\r\n\r\nstack_object.push(3)\r\nstack_object.push(2)\r\nstack_object.push(1)\r\n\r\nprint(stack_object.pop())\r\nprint(stack_object.pop())\r\nprint(stack_object.pop())\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>12. An <strong>instance variable<\/strong> is a property whose existence depends on the creation of an object. Every object can have a different set of instance variables.<\/p>\n<p>Moreover, they can be freely added to and removed from objects during their lifetime. All object instance variables are stored inside a dedicated dictionary named <code><strong>__dict__<\/strong><\/code>, contained in every object separately.<\/p>\n<pre class=\"lang:default decode:true\">class ExampleClass:\r\n    def __init__(self, val = 1):\r\n        self.first = val\r\n\r\n    def set_second(self, val):\r\n        self.second = val\r\n\r\n\r\nexample_object_1 = ExampleClass()\r\nexample_object_2 = ExampleClass(2)\r\n\r\nexample_object_2.set_second(3)\r\n\r\nexample_object_3 = ExampleClass(4)\r\nexample_object_3.third = 5\r\n\r\nprint(example_object_1.__dict__)\r\nprint(example_object_2.__dict__)\r\nprint(example_object_3.__dict__)<\/pre>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>the class named <code>ExampleClass<\/code> has a constructor, which unconditionally creates an instance variable named <code>first<\/code>, and sets it with the value passed through the first argument (from the class user&#8217;s perspective) or the second argument (from the constructor&#8217;s perspective); note the default value of the parameter &#8211; any trick you can do with a regular function parameter can be applied to methods, too;<\/li>\n<li>the class also has a method which creates another instance variable, named <code>second<\/code>;<\/li>\n<li>we&#8217;ve created three objects of the class ExampleClass, but all these instances differ:<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p style=\"padding-left: 40px;\"><code>example_object_1<\/code> only has the property named first;<\/p>\n<p style=\"padding-left: 40px;\"><code>example_object_2<\/code> has two properties: first and second;<\/p>\n<p style=\"padding-left: 40px;\"><code>example_object_3<\/code> has been enriched with a property named third just on the fly, outside the class&#8217;s code &#8211; this is possible and fully permissible.<\/p>\n<p>The program&#8217;s output clearly shows that our assumptions are correct &#8211; here it is:<br \/>\n<code>{'first': 1}<\/code><br \/>\n<code>{'second': 3, 'first': 2}<\/code><br \/>\n<code>{'third': 5, 'first': 4}<\/code><\/p>\n<p>There is one additional conclusion that should be stated here: modifying an instance variable of any object has no impact on all the remaining objects. Instance variables are perfectly isolated from each other.<\/p>\n<p>&nbsp;<\/p>\n<p>13. An<strong> instance variable<\/strong> can be private when its name starts with <strong><code>__<\/code><\/strong>, but don&#8217;t forget that such a property is still accessible from outside the class using a mangled name constructed as<strong><code> _ClassName__PrivatePropertyName<\/code><\/strong>.<\/p>\n<pre class=\"lang:default decode:true\">class ExampleClass:\r\n    def __init__(self, val = 1):\r\n        self.__first = val\r\n\r\n    def set_second(self, val = 2):\r\n        self.__second = val\r\n\r\nexample_object_1 = ExampleClass()\r\nexample_object_2 = ExampleClass(2)\r\nexample_object_2.set_second(3)\r\n\r\nexample_object_3 = ExampleClass(4)\r\nexample_object_3.__third = 5\r\n\r\nprint(example_object_1.__dict__)\r\nprint(example_object_2.__dict__)\r\nprint(example_object_3.__dict__)<\/pre>\n<p>It&#8217;s nearly the same as the previous one. The only difference is in the property names. We&#8217;ve added two underscores (__) in front of them.<\/p>\n<p>Output:<\/p>\n<p><code>{'_ExampleClass__first': 1}<\/code><\/p>\n<p><code>{'_ExampleClass__first': 2, '_ExampleClass__second': 3}<\/code><\/p>\n<p><code>{'_ExampleClass__first': 4, '__third': 5}<\/code><\/p>\n<p>The name is now fully accessible from outside the class. You can run a code like this:<\/p>\n<pre class=\"lang:default decode:true \">print(example_object_1._ExampleClass__first)<\/pre>\n<p>&nbsp;<\/p>\n<p>14. A <strong>class variable<\/strong> is a property which exists in exactly one copy, and doesn&#8217;t need any created object to be accessible. Such variables are not shown as <code>__dict__<\/code> content.<\/p>\n<p>All a class&#8217;s class variables are stored inside a dedicated dictionary named <code>__dict__<\/code>, contained in every class separately.<\/p>\n<pre class=\"lang:default decode:true\">class ExampleClass:\r\n    counter = 0\r\n    def __init__(self, val = 1):\r\n        self.__first = val\r\n        ExampleClass.counter += 1\r\n\r\n\r\nexample_object_1 = ExampleClass()\r\nexample_object_2 = ExampleClass(2)\r\nexample_object_3 = ExampleClass(4)\r\n\r\nprint(example_object_1.__dict__, example_object_1.counter)\r\nprint(example_object_2.__dict__, example_object_2.counter)\r\nprint(example_object_3.__dict__, example_object_3.counter)\r\n\r\n<\/pre>\n<p>Running the code will cause the following output:<br \/>\n<code>{'_ExampleClass__first': 1} 3<\/code><br \/>\n<code>{'_ExampleClass__first': 2} 3<\/code><br \/>\n<code>{'_ExampleClass__first': 4} 3<\/code><\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>class variables aren&#8217;t shown in an object&#8217;s <code>__dict__<\/code> (this is natural as class variables aren&#8217;t parts of an object) but you can always try to look into the variable of the same name, but at the class level<\/li>\n<li>a class variable always presents the same value in all class instances (objects)<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true\">class ExampleClass:\r\n    __counter = 0\r\n    def __init__(self, val = 1):\r\n        self.__first = val\r\n        ExampleClass.__counter += 1\r\n\r\nexample_object_1 = ExampleClass()\r\nexample_object_2 = ExampleClass(2)\r\nexample_object_3 = ExampleClass(4)\r\n\r\nprint(example_object_1.__dict__, example_object_1._ExampleClass__counter)\r\nprint(example_object_2.__dict__, example_object_2._ExampleClass__counter)\r\nprint(example_object_3.__dict__, example_object_3._ExampleClass__counter)<\/pre>\n<p><code>{'_ExampleClass__first': 1} 3<\/code><\/p>\n<p><code>{'_ExampleClass__first': 2} 3<\/code><\/p>\n<p><code>{'_ExampleClass__first': 4} 3<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>15. A function named <code>hasattr(<\/code>) can be used to determine if any object\/class contains a specified property.<\/p>\n<pre class=\"lang:default decode:true\">class ExampleClass:\r\n    def __init__(self, val):\r\n        if val % 2 != 0:\r\n            self.a = 1\r\n        else:\r\n            self.b = 1\r\n\r\n\r\nexample_object = ExampleClass(1)\r\n\r\nprint(example_object.a)\r\nprint(example_object.b)<\/pre>\n<p>As you can see, accessing a non-existing object (class) attribute causes an <code>AttributeError<\/code> exception.<\/p>\n<p><code>1<\/code><br \/>\n<code>Traceback (most recent call last):<\/code><br \/>\n<code>File \".main.py\", line 11, in <\/code><br \/>\n<code>print(example_object.b)<\/code><br \/>\n<code>AttributeError: 'ExampleClass' object has no attribute 'b'<\/code><\/p>\n<p>The <code>try-except<\/code> instruction gives you the chance to avoid issues with non-existent properties.<\/p>\n<pre class=\"lang:default decode:true\">class ExampleClass:\r\n    def __init__(self, val):\r\n        if val % 2 != 0:\r\n            self.a = 1\r\n        else:\r\n            self.b = 1\r\n\r\nexample_object = ExampleClass(1)\r\nprint(example_object.a)\r\n\r\ntry:\r\n    print(example_object.b)\r\nexcept AttributeError:\r\n    pass\r\n<\/pre>\n<p>or utlize the <code>hasattr()<\/code>:<\/p>\n<pre class=\"lang:default decode:true\">class ExampleClass:\r\n    def __init__(self, val):\r\n        if val % 2 != 0:\r\n            self.a = 1\r\n        else:\r\n            self.b = 1\r\n\r\nexample_object = ExampleClass(1)\r\nprint(example_object.a)\r\n\r\nif hasattr(example_object, 'b'):\r\n    print(example_object.b)<\/pre>\n<p>&nbsp;<\/p>\n<p><em>Example:<\/em><\/p>\n<pre class=\"lang:default decode:true\">class Sample:\r\n    gamma = 0 # Class variable.\r\n    def __init__(self):\r\n        self.alpha = 1 # Instance variable.\r\n        self.__delta = 3 # Private instance variable.\r\n\r\n\r\nobj = Sample()\r\nobj.beta = 2  # Another instance variable (existing only inside the \"obj\" instance.)\r\nprint(obj.__dict__)<\/pre>\n<p>The code outputs:<br \/>\n<code>{'alpha': 1, '_Sample__delta': 3, 'beta': 2}<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><em>Example<\/em><\/p>\n<pre class=\"lang:default decode:true\">class A: \r\n    def __init__(self, v): \r\n        pass \r\n\r\na = A(1) \r\nprint(hasattr(a, 'A')) \r\n<\/pre>\n<p><code>False<\/code><\/p>\n<pre class=\"lang:default decode:true\">class A: \r\n    A=1\r\n    def __init__(self): \r\n        self.a = 0 \r\n\r\n \r\nprint(hasattr(A, 'a')) \r\n<\/pre>\n<p><code>False<\/code><\/p>\n<pre class=\"lang:default decode:true \">class A: \r\n    A=1\r\n    def __init__(self): \r\n        self.a = 0 \r\n\r\nb=A()\r\nprint(hasattr(A, 'a')) \r\n<\/pre>\n<p><code>False<\/code><\/p>\n<pre class=\"lang:default decode:true\">class A: \r\n    A=1\r\n    def __init__(self): \r\n        self.a = 0 \r\n\r\nb=A() \r\nprint(hasattr(b, 'A')) \r\n<\/pre>\n<p><code>True<\/code><\/p>\n<pre class=\"lang:default decode:true\">class A: \r\n    A=1\r\n    def __init__(self): \r\n        self.a = 0 \r\n\r\nb=A() \r\nprint(hasattr(b, 'a')) \r\n<\/pre>\n<p><code>True<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>16. A <strong>method<\/strong> is a function embedded inside a class. The first (or only) parameter of each method is usually named <code>self<\/code>, which is designed to identify the object for which the method is invoked in order to access the object&#8217;s properties or invoke its methods. There is one fundamental requirement &#8211; a method is obliged to have<strong> at least one parameter<\/strong> (there are no such thing as parameterless methods &#8211; a method may be invoked without an argument, but not declared without parameters).<\/p>\n<p>If you want the method to accept parameters other than <code>self<\/code>, you should: place them after <code>self<\/code> in the method&#8217;s definition; deliver them during invocation without specifying self (as previously) Just like here:<\/p>\n<pre class=\"lang:default decode:true\">class Classy:\r\n    def method(self, par):\r\n        print(\"method:\", par)\r\n\r\nobj = Classy()\r\nobj.method(1)\r\nobj.method(2)\r\nobj.method(3)<\/pre>\n<p>The code outputs:<br \/>\n<code>method: 1<\/code><br \/>\n<code>method: 2<\/code><br \/>\n<code>method: 3<\/code><\/p>\n<p>The <code>self<\/code> parameter is used <strong>to obtain access to the object&#8217;s instance and class variables<\/strong>.<\/p>\n<pre class=\"lang:default decode:true \">class Classy:\r\n    varia = 2\r\n    def method(self):\r\n        print(self.varia, self.var)\r\n\r\n\r\nobj = Classy()\r\nobj.var = 3\r\nobj.method()<\/pre>\n<p>The code outputs:<br \/>\n<code>2 3<\/code><\/p>\n<p>The <code>self<\/code> parameter is also used <strong>to invoke other object\/class methods from inside the class<\/strong>.<\/p>\n<pre class=\"lang:default decode:true\">class Classy:\r\n    def other(self):\r\n        print(\"other\")\r\n\r\n    def method(self):\r\n        print(\"method\")\r\n        self.other()\r\n\r\nobj = Classy()\r\nobj.method()\r\n<\/pre>\n<p>The code outputs:<br \/>\n<code>method<\/code><br \/>\n<code>other<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>17. If a class contains a constructor (a method named <code>__init__<\/code>) it cannot return any value and cannot be invoked directly.<\/p>\n<p>Everything we&#8217;ve said about property name mangling applies to method names, too &#8211; a method whose name starts with <code>__<\/code> is (partially) hidden. The example shows this effect:<\/p>\n<pre class=\"lang:default decode:true\">class Classy:\r\n    def visible(self):\r\n        print(\"visible\")\r\n    \r\n    def __hidden(self):\r\n        print(\"hidden\")\r\n\r\nobj = Classy()\r\nobj.visible()\r\n\r\ntry:\r\n    obj.__hidden()\r\nexcept:\r\n    print(\"failed\")\r\n\r\nobj._Classy__hidden()<\/pre>\n<p><code>visible<\/code><br \/>\n<code>failed<\/code><br \/>\n<code>hidden<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>18.\u00a0Each Python class and each Python object is pre-equipped with a set of useful attributes which can be used to examine its capabilities.<\/p>\n<ul>\n<li>One of these &#8211; it&#8217;s the <strong><code>__dict__<\/code> <\/strong>property.<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true\">class Classy:\r\n    varia = 1\r\n    def __init__(self):\r\n        self.var = 2\r\n\r\n    def method(self):\r\n        pass\r\n\r\n    def __hidden(self):\r\n        pass\r\n\r\nobj = Classy()\r\n\r\nprint(obj.__dict__)\r\nprint(Classy.__dict__)\r\n<\/pre>\n<p>Output:<\/p>\n<pre class=\"lang:default decode:true \">{'var': 2}\r\n\r\n{'__module__': '__main__', 'varia': 1, '__init__': &lt;function Classy.__init__ at 0x7fb94adea320&gt;, 'method': &lt;function Classy.method at 0x7fb94adeaef0&gt;, '_Classy__hidden': &lt;function Classy.__hidden at 0x7fb94adeaf80&gt;, '__dict__': &lt;attribute '__dict__' of 'Classy' objects&gt;, '__weakref__': &lt;attribute '__weakref__' of 'Classy' objects&gt;, '__doc__': None}<\/pre>\n<p>&nbsp;<\/p>\n<ul>\n<li>Another built-in property worth mentioning is <strong><code>__name__<\/code><\/strong>, which is a string. The property contains the name of the class. \u00a0The <strong><code>__name__<\/code> <\/strong>attribute is absent from the object &#8211; <strong>it exists only inside classes<\/strong>.<\/li>\n<\/ul>\n<p>If you want to find the class of a particular object, you can use a function named <code>type()<\/code>, which is able (among other things) to find a class which has been used to instantiate any object.<\/p>\n<pre class=\"lang:default decode:true\">class Classy:\r\n    pass\r\n\r\nprint(Classy.__name__)\r\nobj = Classy()\r\nprint(type(obj).__name__)\r\n<\/pre>\n<p>The code outputs:<br \/>\n<code>Classy<\/code><br \/>\n<code>Classy<\/code><\/p>\n<p>Note that a statement like this one:<\/p>\n<pre class=\"lang:default decode:true \">print(obj.__name__)<\/pre>\n<p>will cause an error.<\/p>\n<p>Example:<\/p>\n<pre class=\"lang:default decode:true\">class Sample:\r\n    def __init__(self):\r\n        self.name = Sample.__name__\r\n    def myself(self):\r\n        print(\"My name is \" + self.name + \" living in a \" + Sample.__module__)\r\n\r\n\r\nobj = Sample()\r\nobj.myself()\r\n<\/pre>\n<p>The code outputs:<\/p>\n<p><code>My name is Sample living in a __main__<\/code><\/p>\n<p>&nbsp;<\/p>\n<ul>\n<li>Additionally, a property named <strong><code>__module__<\/code> <\/strong>stores the name of the module in which the class has been declared,<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true\">class Classy:\r\n    pass\r\n\r\nprint(Classy.__module__)\r\nobj = Classy()\r\nprint(obj.__module__)<\/pre>\n<p>The code outputs:<br \/>\n<code>__main__<\/code><br \/>\n<code>__main__<\/code><\/p>\n<p>Any module named <code>__main__<\/code> is actually not a module, but the file currently being run.<\/p>\n<p>&nbsp;<\/p>\n<ul>\n<li>the property named <strong><code>__bases__<\/code> <\/strong>is a tuple containing a class&#8217;s superclasses.<\/li>\n<\/ul>\n<p>Note: only classes have this attribute &#8211; objects don&#8217;t.<\/p>\n<pre class=\"lang:default decode:true\">class SuperOne:\r\n    pass\r\n\r\nclass SuperTwo:\r\n    pass\r\n\r\nclass Sub(SuperOne, SuperTwo):\r\n    pass\r\n\r\ndef printBases(cls):\r\n    print('( ', end='')\r\n\r\n    for x in cls.__bases__:\r\n        print(x.__name__, end=' ')\r\n    print(')')\r\n\r\nprintBases(SuperOne)\r\nprintBases(SuperTwo)\r\nprintBases(Sub)\r\n<\/pre>\n<p>It will output:<br \/>\n<code>( object )<\/code><br \/>\n<code>( object )<\/code><br \/>\n<code>( SuperOne SuperTwo )<\/code><\/p>\n<p>Note: <strong>a class without explicit superclasses points to object<\/strong> (a predefined Python class) as its direct ancestor.<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>1. A method named <code>__str__()<\/code> is responsible for <b>converting an object&#8217;s contents into a <\/b>(more or less) <b>readable string<\/b>. You can redefine it if you want your object to be able to present itself in a more elegant form. For example:<\/p>\n<pre class=\"lang:default decode:true \">class Mouse:\r\n    def __init__(self, name):\r\n        self.my_name = name\r\n\r\n    def __str__(self):\r\n        return self.my_name\r\n\r\nthe_mouse = Mouse('mickey')\r\nprint(the_mouse)<\/pre>\n<p><code>mickey<\/code><\/p>\n<p>If the <code>__str()__<\/code> method is not defined for object:<\/p>\n<pre class=\"lang:default decode:true \">class Jedi:\r\n    def __init__(self, name):\r\n        self.name = name\r\n    def Print(self):\r\n        return self.name\r\n     \r\n     \r\nLuke = Jedi('Luke')\r\n print(Luke)<\/pre>\n<p>invocating the <code>print()<\/code> function on object Luke will invoke the default <code>__str()__<\/code> method which returns the following string :<\/p>\n<p><code>&lt;__main__.Jedi object at 0x7f910c9d9390&gt;<\/code><\/p>\n<p>To get a result different from the default string above, the <code>__str__()<\/code> method would need to be defined in the Jedi class.<\/p>\n<pre class=\"lang:default decode:true \">    class Jedi:\r\n        def __init__(self, name):\r\n            self.name = name\r\n        def Print(self):\r\n            return self.name\r\n     \r\n    class Sith:\r\n        def __init__(self, name):\r\n            self.name = name\r\n        def __str__(self):      # I defined the __str()__ method for class Sith \r\n            return self.name\r\n     \r\n    Luke = Jedi('Luke')\r\n    print(Luke)                 # &lt;__main__.Jedi object at 0x7f910c9d9390&gt;\r\n     \r\n    Vader = Sith('Vader')\r\n    print(Vader)                # Vader<\/pre>\n<p>&nbsp;<\/p>\n<p>2. A function named <code>issubclass(Class_1, Class_2)<\/code> is able to determine if <code>Class_1<\/code> is a <b>subclass<\/b> of <code>Class_2<\/code>. For example:<\/p>\n<pre class=\"lang:default decode:true\">class Mouse:\r\n    pass\r\n\r\nclass LabMouse(Mouse):\r\n    pass\r\n\r\nprint(issubclass(Mouse, LabMouse), issubclass(LabMouse, Mouse))  \r\n# Prints \"False True\"<\/pre>\n<p>&nbsp;<\/p>\n<p>3. A function named <code>isinstance(Object, Class)<\/code> returns <span style=\"font-family: Courier New;\">True<\/span> if the object is an instance of the class, or <span style=\"font-family: Courier New;\">False<\/span> otherwise.. For example:<\/p>\n<pre class=\"lang:default decode:true\">class Mouse:\r\n    pass\r\n\r\nclass LabMouse(Mouse):\r\n    pass\r\n\r\nmickey = Mouse()\r\nprint(isinstance(mickey, Mouse), isinstance(mickey, LabMouse))  \r\n# Prints \"True False\".<\/pre>\n<p>&nbsp;<\/p>\n<p>4. A operator called <code>is<\/code> checks if two variables refer to <b>the same object<\/b>. For example:<\/p>\n<pre class=\"lang:default decode:true\">class Mouse:\r\n    pass\r\n\r\nmickey = Mouse()\r\nminnie = Mouse()\r\ncloned_mickey = mickey\r\nprint(mickey is minnie, mickey is cloned_mickey)  \r\n# Prints \"False True\".\r\n\r\n<\/pre>\n<p>Don&#8217;t forget that <strong>variables don&#8217;t store the objects themselves, but only the handles pointing to the internal Python memory<\/strong>.<\/p>\n<pre class=\"lang:default decode:true\">class SampleClass:\r\n    def __init__(self, val):\r\n        self.val = val\r\n\r\nobject_1 = SampleClass(0)\r\nprint(object_1.val)\r\n\r\nobject_2 = SampleClass(2)\r\n\r\nobject_3 = object_1\r\nprint(object_1.val)\r\n\r\nobject_3.val += 1\r\nprint(object_1.val)\r\n\r\nprint(object_1 is object_2)\r\nprint(object_2 is object_3)\r\nprint(object_3 is object_1)\r\nprint(object_1.val, object_2.val, object_3.val)\r\n\r\nstring_1 = \"Mary had a little \"\r\nstring_2 = \"Mary had a little lamb\"\r\nstring_1 += \"lamb\"\r\n\r\nprint(string_1 == string_2, string_1 is string_2)<\/pre>\n<p><code>0<\/code><\/p>\n<p><code>0<\/code><\/p>\n<p><code>1<\/code><\/p>\n<p><code>False<\/code><\/p>\n<p><code>False<\/code><\/p>\n<p><code>True<\/code><\/p>\n<p><code>1 2 1<\/code><\/p>\n<p><code>True False<\/code><\/p>\n<p>The results prove that <code>object_1<\/code> and <code>object_3<\/code> are actually the same objects, while <code>string_1<\/code> and <code>string_2<\/code> aren&#8217;t, despite their contents being the same.<\/p>\n<p>&nbsp;<\/p>\n<p>5. A parameterless function named <code>super()<\/code> returns a <b>reference to the nearest superclass of the class<\/b>. For example:<\/p>\n<pre class=\"lang:default decode:true\">class Mouse:\r\n    def __str__(self):\r\n        return \"Mouse\"\r\n\r\nclass LabMouse(Mouse):\r\n    def __str__(self):\r\n        return \"Laboratory \" + super().__str__()\r\n\r\ndoctor_mouse = LabMouse();\r\nprint(doctor_mouse)  # Prints \"Laboratory Mouse\".\r\n\r\n<\/pre>\n<p>Note: you can use this mechanism not only to <strong>invoke the superclass constructor, but also to get access to any of the resources available inside the superclass<\/strong>.<\/p>\n<p>&nbsp;<\/p>\n<p>6. Methods as well as instance and class variables defined in a superclass are <b>automatically inherited<\/b> by their subclasses. For example:<\/p>\n<pre class=\"lang:default decode:true\">class Mouse:\r\n    Population = 0\r\n    def __init__(self, name):\r\n        Mouse.Population += 1\r\n        self.name = name\r\n\r\n    def __str__(self):\r\n        return \"Hi, my name is \" + self.name\r\n\r\nclass LabMouse(Mouse):\r\n    pass\r\n\r\nprofessor_mouse = LabMouse(\"Professor Mouser\")\r\nprint(professor_mouse, Mouse.Population)  # Prints \"Hi, my name is Professor Mouser 1\"\r\n\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>7. In order to find any object\/class property, Python looks for it inside:<\/p>\n<ul>\n<li>the object itself;<\/li>\n<li>all classes involved in the object&#8217;s inheritance line from bottom to top;<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true\">class Level1:\r\n    var = 100\r\n    def fun(self):\r\n        return 101\r\n\r\nclass Level2(Level1):\r\n    var = 200\r\n    def fun(self):\r\n        return 201\r\n\r\nclass Level3(Level2):\r\n    pass\r\n\r\nobj = Level3()\r\n\r\nprint(obj.var, obj.fun())\r\n<\/pre>\n<p><code>200 201<\/code><\/p>\n<ul>\n<li>if there is more than one class on a particular inheritance path, Python scans them from left to right;<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true\">class Left:\r\n    var = \"L\"\r\n    var_left = \"LL\"\r\n    def fun(self):\r\n        return \"Left\"\r\n\r\nclass Right:\r\n    var = \"R\"\r\n    var_right = \"RR\"\r\n    def fun(self):\r\n        return \"Right\"\r\n\r\nclass Sub(Left, Right):\r\n    pass\r\n\r\nobj = Sub()\r\n\r\nprint(obj.var, obj.var_left, obj.var_right, obj.fun())<\/pre>\n<p><code>L LL RR Left<\/code><\/p>\n<p>&nbsp;<\/p>\n<ul>\n<li>if both of the above fail, the <code>AttributeError<\/code> exception is raised.<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true\">class Level1:\r\n    variable_1 = 100\r\n    def __init__(self):\r\n        self.var_1 = 101\r\n    def fun_1(self):\r\n        return 102\r\n\r\nclass Level2(Level1):\r\n    variable_2 = 200\r\n    def __init__(self):\r\n        super().__init__()\r\n        self.var_2 = 201\r\n    def fun_2(self):\r\n        return 202\r\n\r\nclass Level3(Level2):\r\n    variable_3 = 300\r\n    def __init__(self):\r\n        super().__init__()\r\n        self.var_3 = 301\r\n    def fun_3(self):\r\n        return 302\r\n\r\nobj = Level3()\r\n\r\nprint(obj.variable_1, obj.var_1, obj.fun_1())\r\nprint(obj.variable_2, obj.var_2, obj.fun_2())\r\nprint(obj.variable_3, obj.var_3, obj.fun_3())<\/pre>\n<p><code>100 101 102<\/code><\/p>\n<p><code>200 201 202<\/code><\/p>\n<p><code>300 301 302<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>8. If any of the subclasses defines a method\/class variable\/instance variable of the same name as existing in the superclass, the new name <b>overrides<\/b> any of the previous instances of the name. For example:<\/p>\n<pre class=\"lang:default decode:true \">class Mouse:\r\n    def __init__(self, name):\r\n        self.name = name\r\n\r\n    def __str__(self):\r\n        return \"My name is \" + self.name\r\n\r\nclass AncientMouse(Mouse):\r\n    def __str__(self):\r\n        return \"Meum nomen est \" + self.name\r\n\r\nmus = AncientMouse(\"Caesar\")  \r\nprint(mus) \r\n# Prints \"Meum nomen est Caesar\"\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>9. The situation in which <strong>the subclass is able to modify its superclass behavior<\/strong> (just like in the example)<strong> is called polymorphism<\/strong>. Polymorphism helps the developer to keep the code clean and consistent.<\/p>\n<pre class=\"lang:default decode:true\">class One:\r\n    def do_it(self):\r\n        print(\"do_it from One\")\r\n\r\n    def doanything(self):\r\n        self.do_it()\r\n\r\nclass Two(One):\r\n    def do_it(self):\r\n        print(\"do_it from Two\")\r\n\r\none = One()\r\ntwo = Two()\r\n\r\none.doanything()\r\ntwo.doanything()\r\n<\/pre>\n<p><code>do_it from One<\/code><\/p>\n<p><code>do_it from Two<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><em>Example:<\/em><\/p>\n<pre class=\"lang:default decode:true \">class A: \r\n    def __init__(self, v=2): \r\n        self.v = v\r\n        \r\n    def set(self, v=1): \r\n        print(\"self.v=\", self.v)\r\n        self.v += v \r\n        return self.v\r\n        \r\na = A() \r\nb = a \r\nprint(\"b=\", b.v) \r\n\r\nb.set() \r\nprint(\"a=\", a.v)<\/pre>\n<p><code>b= 2<\/code><br \/>\n<code>self.v= 2<\/code><br \/>\n<code>a= 3<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><strong>Reflection and introspection<\/strong><\/p>\n<p>Introspection\u00a0 is the ability of a program to examine the type or properties of an object at runtime;<img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-6061 aligncenter\" src=\"http:\/\/miro.borodziuk.eu\/wp-content\/uploads\/Introspection.jpg\" alt=\"\" width=\"226\" height=\"441\" srcset=\"http:\/\/miro.borodziuk.eu\/wp-content\/uploads\/Introspection.jpg 226w, http:\/\/miro.borodziuk.eu\/wp-content\/uploads\/Introspection-154x300.jpg 154w\" sizes=\"(max-width: 226px) 100vw, 226px\" \/><\/p>\n<p>Reflection, which goes a step further, and is the ability of a program to manipulate the values, properties and\/or functions of an object at runtime.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-6062 aligncenter\" src=\"http:\/\/miro.borodziuk.eu\/wp-content\/uploads\/Reflection.jpg\" alt=\"\" width=\"410\" height=\"369\" srcset=\"http:\/\/miro.borodziuk.eu\/wp-content\/uploads\/Reflection.jpg 410w, http:\/\/miro.borodziuk.eu\/wp-content\/uploads\/Reflection-300x270.jpg 300w\" sizes=\"(max-width: 410px) 100vw, 410px\" \/><\/p>\n<p><em><br \/>\nExercise 1<\/em><\/p>\n<p>Can you name one of your classes just &#8220;class&#8221;?<\/p>\n<p><em>No, you can&#8217;t \u2013 class is a keyword!<\/em><\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 2<\/em><\/p>\n<p>Assuming that there is a class named Snakes, write the very first line of the Python class declaration, expressing the fact that the new class is actually a subclass of Snake.<\/p>\n<pre class=\"lang:default decode:true \">class Python(Snakes):<\/pre>\n<p>&nbsp;<\/p>\n<p><em>Exercise 3<\/em><\/p>\n<p>Something is missing from the following declaration \u2013 what?<\/p>\n<pre class=\"lang:default decode:true\">class Snakes:\r\n  def __init__():\r\n    self.sound = 'Sssssss'<\/pre>\n<p>The<strong><code> __init__()<\/code><\/strong> constructor lacks the obligatory parameter (we should name it <code><strong>self<\/strong> <\/code>to stay compliant with the standards).<\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 4<\/em><\/p>\n<p>Modify the code to guarantee that the venomous property is private.<\/p>\n<pre class=\"lang:default decode:true \">class Snakes:\r\n  def __init__(self):\r\n    self.venomous = True<\/pre>\n<p>&nbsp;<\/p>\n<p>The code should look as follows:<\/p>\n<pre class=\"lang:default decode:true \">class Snakes:\r\n  def __init__(self):\r\n    self.__venomous = True<\/pre>\n<p>&nbsp;<\/p>\n<p><em>Exercise 5<\/em><\/p>\n<p>Which of the Python class properties are instance variables and which are class variables? Which of them are private?<\/p>\n<pre class=\"lang:default decode:true\">class Python:\r\n  population = 1\r\n  victims = 0\r\n  def __init__(self):\r\n    self.length_ft = 3\r\n    self.__venomous = False<\/pre>\n<p><code>population<\/code> and <code>victims<\/code> are <em>class variables<\/em>, while <code>length<\/code> and <code>__venomous<\/code> are<em> instance variables<\/em> (the latter is also private).<\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 6<\/em><\/p>\n<p>You&#8217;re going to negate the <code>__venomous<\/code> property of the <code>version_2<\/code> object, ignoring the fact that the property is private. How will you do this?<\/p>\n<pre class=\"lang:default decode:true \">version_2 = Python()<\/pre>\n<p>&nbsp;<\/p>\n<pre class=\"lang:default decode:true \">version_2._Python__venomous = not version_2._Python__venomous<\/pre>\n<p>&nbsp;<\/p>\n<p><em>Exercise 7<\/em><\/p>\n<p>Write an expression which checks if the <code>version_2<\/code> object contains an instance property named <code>constrictor<\/code> (yes, constrictor!).<\/p>\n<pre class=\"lang:default decode:true \">hasattr(version_2, 'constrictor')<\/pre>\n<p>&nbsp;<\/p>\n<p><em>Exercise 8<\/em><\/p>\n<p>The declaration of the Snake class is given below. Enrich the class with a method named <code>increment()<\/code>, adding 1 to the victims property.<\/p>\n<pre class=\"lang:default decode:true \">class Snake:\r\n  def __init__(self):\r\n    self.victims = 0<\/pre>\n<p>&nbsp;<\/p>\n<pre class=\"lang:default decode:true\">class Snake:\r\n  def __init__(self):\r\n    self.victims = 0\r\n\r\n  def increment(self):\r\n    self.victims += 1<\/pre>\n<p>&nbsp;<\/p>\n<p><em>Exercise 9<\/em><\/p>\n<p>Redefine the Snake class constructor so that is has a parameter to initialize the victims field with a value passed to the object during construction.<\/p>\n<pre class=\"lang:default decode:true\">class Snake:\r\n  def __init__(self, victims):\r\n  self.victims = victims<\/pre>\n<p>&nbsp;<\/p>\n<p><em>Exercise 10<\/em><\/p>\n<p>Can you predict the output of the following code?<\/p>\n<pre class=\"lang:default decode:true\">class Snake:\r\n  pass\r\n\r\nclass Python(Snake):\r\n  pass\r\n\r\nprint(Python.__name__, 'is a', Snake.__name__)\r\nprint(Python.__bases__[0].__name__, 'can be a', Python.__name__)<\/pre>\n<p>&nbsp;<\/p>\n<p><code>Python is a Snake<\/code><br \/>\n<code>Snake can be a Python<\/code><\/p>\n<p>&nbsp;<\/p>\n<h1>Exercises<\/h1>\n<p><b>Scenario<\/b><\/p>\n<p>Assume that the following piece of code has been successfully executed:<\/p>\n<pre class=\"lang:default decode:true\">class Dog:\r\n    kennel = 0\r\n    def __init__(self, breed):\r\n        self.breed = breed\r\n        Dog.kennel += 1\r\n    def __str__(self):\r\n        return self.breed + \" says: Woof!\"\r\n\r\n\r\nclass SheepDog(Dog):\r\n    def __str__(self):\r\n        return super().__str__() + \" Don't run away, Little Lamb!\"\r\n\r\n\r\nclass GuardDog(Dog):\r\n    def __str__(self):\r\n        return super().__str__() + \" Stay where you are, Mister Intruder!\"\r\n\r\n\r\nrocky = SheepDog(\"Collie\")\r\nluna = GuardDog(\"Dobermann\")<\/pre>\n<p>&nbsp;<\/p>\n<p>Exercise 11<\/p>\n<p>What is the expected output of the following piece of code?<\/p>\n<pre class=\"lang:default decode:true \">print(rocky)\r\nprint(luna)<\/pre>\n<p>&nbsp;<\/p>\n<p><code>Collie says: Woof! Don't run away, Little Lamb!<\/code><br \/>\n<code>Dobermann says: Woof! Stay where you are, Mister Intruder!<\/code><\/p>\n<p>Exercise 12<\/p>\n<p>What is the expected output of the following piece of code?<\/p>\n<pre class=\"lang:default decode:true \">print(issubclass(SheepDog, Dog), issubclass(SheepDog, GuardDog))\r\nprint(isinstance(rocky, GuardDog), isinstance(luna, GuardDog))<\/pre>\n<p>&nbsp;<\/p>\n<p><code>True False<\/code><br \/>\n<code>False True<\/code><\/p>\n<p>Exercise 13<\/p>\n<p>What is the expected output of the following piece of code?<\/p>\n<pre class=\"lang:default decode:true \">print(luna is luna, rocky is luna)\r\nprint(rocky.kennel)<\/pre>\n<p>&nbsp;<\/p>\n<p><code>True False<\/code><br \/>\n<code>2<\/code><\/p>\n<p>Exercise 14<\/p>\n<p>Define a <code>SheepDog<\/code>&#8216;s subclass named <code>LowlandDog<\/code>, and equip it with an <code>__str__()<\/code> method overriding an inherited method of the same name. The new dog&#8217;s <code>__str__()<\/code> method should return the string &#8220;Woof! I don&#8217;t like mountains!&#8221; .<\/p>\n<pre class=\"lang:default decode:true \">class LowlandDog(SheepDog):\r\n  def __str__(self):\r\n    return Dog.__str__(self) + \" I don't like mountains!\"<\/pre>\n<p>&nbsp;<\/p>\n<p>Excercise 15<\/p>\n<p>What is the expected output of the following code snippet ?<\/p>\n<pre class=\"lang:default decode:true \">    class Vegetable:\r\n        pass\r\n     \r\n    class RootVegetable(Vegetable):\r\n        pass\r\n     \r\n    class Potato(RootVegetable):\r\n        pass\r\n     \r\n    print(Potato.__bases__)<\/pre>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-correct--PLOEU\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-incorrect--vFyOv\" data-purpose=\"answer\">\n<div>\n<p><code>__bases__<\/code>\u00a0 is a predefined property of a <strong>class. <\/strong>It is a <strong>tuple <\/strong>and contains the classes (not the class names) which are <strong>direct superclasses <\/strong>of the class.<\/p>\n<p>Direct superclass of the <code>Potato<\/code> class is : <code>RootVegetable<\/code>.<\/p>\n<p>So, correct answer is :<\/p>\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<p><code><strong><span class=\"pun\">(&lt;<\/span><span class=\"kwd\">class<\/span> <span class=\"str\">'__main__.RootVegetable'<\/span><\/strong><span class=\"pun\"><strong>&gt;,)<\/strong><\/span><\/code><\/p>\n<p>Not correct answer is :<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<p><code><span class=\"pun\">(&lt;<\/span><span class=\"kwd\">class<\/span> <span class=\"str\">'__main__.RootVegetable'<\/span><span class=\"pun\">&gt;,<\/span> <span class=\"pun\">&lt;<\/span><span class=\"kwd\">class<\/span> <span class=\"str\">'__main__.Vegetable'<\/span><span class=\"pun\">&gt;)<\/span><\/code><\/p>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Excercise 16<\/p>\n<p>What is the expected output of the following code snippet ?<\/p>\n<pre class=\"lang:default decode:true \">    class Sith:\r\n        darkside= True\r\n        def __init__(self, x, y):\r\n            self.name = x\r\n            self.lightsaber = 1\r\n            self.__son = y\r\n        def __str__(self):\r\n            return self.name\r\n     \r\n    Vader = Sith(\"Vader\", \"Luke\")\r\n    Vader.__daughter = 'Leia'\r\n    print(Vader.__dict__)\r\n\r\n\r\n<\/pre>\n<p><code>__dict__<\/code> is a predefined property of all Python objects : this variable is a dictionary and contains the names and values of all the variables the object is currently carrying.<\/p>\n<p>A few things to remember about <code>__dict__<\/code> for an object :<\/p>\n<p>&#8211; class variable will not appear in the <code>__dict__<\/code> variable of an object.<\/p>\n<p>&#8211; private instance variable defined inside the class will appear in the dictionary using &#8220;name mangling&#8221;, i.e. : <code>_className__variable<\/code> where className is the name of the class where that private instance variable is defined.<\/p>\n<p>&#8211; private instance variable defined outside the class will appear in the dictionary as <code>__variable<\/code><\/p>\n<p>Correct answer is :<\/p>\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<p><strong><code><span class=\"pun\">{<\/span><span class=\"str\">'name'<\/span><span class=\"pun\">:<\/span> <span class=\"str\">'Vader'<\/span><span class=\"pun\">,<\/span> <span class=\"str\">'lightsaber'<\/span><span class=\"pun\">:<\/span> <span class=\"lit\">1<\/span><span class=\"pun\">,<\/span> <span class=\"str\">'_Sith__son'<\/span><span class=\"pun\">:<\/span> <span class=\"str\">'Luke'<\/span><span class=\"pun\">,<\/span> <span class=\"str\">'__daughter'<\/span><span class=\"pun\">:<\/span> <span class=\"str\">'Leia'<\/span><span class=\"pun\">}<\/span><\/code><\/strong><\/p>\n<\/div>\n<\/div>\n<p><strong>(<code>son <\/code>is a private instance variable defined inside the class; <code>daughter <\/code>is a private instance variable defined outside the class; variable <code>darkside <\/code>does not show up since it is a class variable).<\/strong><\/p>\n<p>Not correct:<\/p>\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<p><code><span class=\"pun\">{<\/span><span class=\"str\">'name'<\/span><span class=\"pun\">:<\/span> <span class=\"str\">'Vader'<\/span><span class=\"pun\">,<\/span> <span class=\"str\">'lightsaber'<\/span><span class=\"pun\">:<\/span> <span class=\"lit\">1<\/span><span class=\"pun\">,<\/span> <span class=\"str\">'_Sith__son'<\/span><span class=\"pun\">:<\/span> <span class=\"str\">'Luke'<\/span><span class=\"pun\">,<\/span> <span class=\"str\">'_Sith__daughter'<\/span><span class=\"pun\">:<\/span> <span class=\"str\">'Leia'<\/span><span class=\"pun\">}<\/span><\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Ex. 17<\/p>\n<div id=\"question-prompt\" class=\" ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>You want to create a new class <code>Class2<\/code>, as a subclass of class <code>Class1<\/code>.<\/p>\n<p>You want the constructor of <code>Class2<\/code>\u00a0 to be exactly the same as the one from <code>Class1<\/code> (this constructor has two parameters : <code>self <\/code>and <code>val<\/code>).<\/p>\n<p>Which code snippet below would comply with the above requirements ?<\/p>\n<pre class=\"lang:default decode:true\">class Class2(Class1):\r\n   pass<\/pre>\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<p>With this code snippet, <code>Class2 <\/code>will inherit the <strong>constructor <\/strong>(and any other methods) of <strong>Class1 <\/strong>as-is.<\/p>\n<p>As a reminder, a constructor is a method in a class that will be invoked automatically and implicitly when the object of the class is instantiated. This method is created as\u00a0 <code>__init__<\/code>.<\/p>\n<p>An alternative to this answer could have been:<\/p>\n<pre class=\"lang:default decode:true \">class Class2(Class1):\r\n   def __init__(self, val):\r\n       Class1.__init__(self, val)<\/pre>\n<p>or:<\/p>\n<pre class=\"lang:default decode:true \">class Class2(Class1):\r\n   def __init__(self, val):\r\n        super().__init__(val)<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Ex. 18<\/p>\n<p>What is the expected output of the following code snippet ?<\/p>\n<pre class=\"lang:default decode:true \">    class A:\r\n        def __init__(self, x=5):\r\n            self.x = x\r\n     \r\n    class B(A):\r\n        def __init__(self, y=2):\r\n            super().__init__(y) \r\n        def set(self, y):\r\n            self.x = y + 3\r\n            return self.x\r\n     \r\n    b = B()\r\n    print(b.set(b.x + 2))<\/pre>\n<p>&nbsp;<\/p>\n<p><strong>Explanation:<\/strong><\/p>\n<p><code>b<\/code> is an object from class <code>B<\/code>, which is a subclass of class <code>A<\/code>.<\/p>\n<p><code>B<\/code>&#8216;s constructor calls its direct superclass&#8217;s constructor via line <code>super().__init__(y) <\/code>\u00a0 (<code>super()<\/code> returns a reference to the direct superclass). so, object <code>b<\/code> inherits property &#8216;<code>x<\/code>&#8216; and its value is set to <code>2<\/code> since this is the default value in <code>B<\/code>&#8216;s constructor when no parameter is provided.<\/p>\n<p>So, after object <code>b<\/code> is created, <code>b.x<\/code> has a value of <code>2<\/code>.<\/p>\n<p>So, call to <code>b.set(b.x + 2)<\/code>\u00a0 is equivalent to <code>b.set(4)<\/code>. As per the definition of method <code>set()<\/code> in class <code>B<\/code>, <code>set(y)<\/code> will return property <code>x<\/code> after <code>x<\/code> has been assigned value <code>y + 3<\/code> &#8211; in the case where <code>y=4<\/code> then the value returned is <code>7<\/code>.<\/p>\n<p>So final answer is : <code>7<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>Ex. 19<\/p>\n<p>What is the expected output of the following code?<\/p>\n<pre class=\"lang:default decode:true \">    class A:\r\n        X = 2\r\n        def __init__(self, a, b):\r\n            self.x = a + b\r\n            self.__y = a - b\r\n     \r\n    a = A(3,2)\r\n    a.__z = 0\r\n    print(a.__dict__)<\/pre>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<p><span class=\"pun\">A:<code> {<\/code><\/span><code><span class=\"str\">'x'<\/span><span class=\"pun\">:<\/span> <span class=\"lit\">5<\/span><span class=\"pun\">,<\/span> <span class=\"str\">'y'<\/span><span class=\"pun\">:<\/span> <span class=\"lit\">1<\/span><span class=\"pun\">,<\/span> <span class=\"str\">'z'<\/span><span class=\"pun\">:<\/span> <span class=\"lit\">0<\/span><span class=\"pun\">,<\/span> <span class=\"str\">'X'<\/span><span class=\"pun\">:<\/span> <span class=\"lit\">2<\/span><span class=\"pun\">}<\/span><\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-correct--PLOEU\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<p><span class=\"pun\">B: <code>{<\/code><\/span><code><span class=\"str\">'x'<\/span><span class=\"pun\">:<\/span> <span class=\"lit\">5<\/span><span class=\"pun\">,<\/span> <span class=\"str\">'_A__y'<\/span><span class=\"pun\">:<\/span> <span class=\"lit\">1<\/span><span class=\"pun\">,<\/span> <span class=\"str\">'__z'<\/span><span class=\"pun\">:<\/span> <span class=\"lit\">0<\/span><span class=\"pun\">}<\/span><\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<p><span class=\"pun\">C: <code>{<\/code><\/span><code><span class=\"str\">'x'<\/span><span class=\"pun\">:<\/span> <span class=\"lit\">5<\/span><span class=\"pun\">,<\/span> <span class=\"str\">'_A__y'<\/span><span class=\"pun\">:<\/span> <span class=\"lit\">1<\/span><span class=\"pun\">,<\/span> <span class=\"str\">'__z'<\/span><span class=\"pun\">:<\/span> <span class=\"lit\">0<\/span><span class=\"pun\">,<\/span> <span class=\"str\">'X'<\/span><span class=\"pun\">:<\/span> <span class=\"lit\">2<\/span><span class=\"pun\">}<\/span><\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<p><span class=\"pun\">D: <code>{<\/code><\/span><code><span class=\"str\">'x'<\/span><span class=\"pun\">:<\/span> <span class=\"lit\">5<\/span><span class=\"pun\">,<\/span> <span class=\"str\">'__y'<\/span><span class=\"pun\">:<\/span> <span class=\"lit\">1<\/span><span class=\"pun\">,<\/span> <span class=\"str\">'__z'<\/span><span class=\"pun\">:<\/span> <span class=\"lit\">0<\/span><span class=\"pun\">}<\/span><\/code><\/p>\n<\/div>\n<p>Explanation:<\/p>\n<p><code>__dict__<\/code>\u00a0 is a &#8220;built-in&#8221; property of an object : it is a dictionary that includes the name of the object&#8217;s variables (as key) and their corresponding values.<\/p>\n<p>A few things to remember about <code>__dict__<\/code> for an object :<\/p>\n<p>&#8211; class variables are not included<\/p>\n<p>&#8211; private instance variables are included &#8211; if they have been defined within the class, name mangling is used to refer to them<\/p>\n<p>&#8211; instance variables defined outside of the class are included &#8211; if they are private, name mangling is not needed to refer to them<\/p>\n<p>Based on the above, the only possible answer is :<\/p>\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<p><span class=\"pun\">B:<code> {<\/code><\/span><code><span class=\"str\">'x'<\/span><span class=\"pun\">:<\/span> <span class=\"lit\">5<\/span><span class=\"pun\">,<\/span> <span class=\"str\">'_A__y'<\/span><span class=\"pun\">:<\/span> <span class=\"lit\">1<\/span><span class=\"pun\">,<\/span> <span class=\"str\">'__z'<\/span><span class=\"pun\">:<\/span> <span class=\"lit\">0<\/span><span class=\"pun\">}<\/span><\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Ex. 20<\/p>\n<p>Consider the code below :<\/p>\n<pre class=\"lang:default decode:true \">    class Alpha:                    # line 1\r\n        def __init__(self, val):    # line 2\r\n            self.a = val            # line 3\r\n                                    # line 4\r\n    class Beta(Alpha):              # line 5\r\n        #insert code here           # line 6\r\n                                    # line 7\r\n    beta = Beta(\"beta\")             # line 8\r\n    print(beta)                     # line 9<\/pre>\n<p>Which code snippet would you insert in line 6 so the above code produce the following output :<\/p>\n<p><code>I am beta, son of Alpha <\/code><\/p>\n<p>A.<\/p>\n<pre class=\"lang:default decode:true\">def __str__(self):\r\n   return \"I am \" + self.a + \", son of \" + Beta.__bases__[0].__name__<\/pre>\n<p>B.<\/p>\n<pre class=\"lang:default decode:true \">def __str__(self):\r\n    return \"I am \" + self.a + \", son of \" + Beta.super().__name__<\/pre>\n<p>C.<\/p>\n<pre class=\"lang:default decode:true \">def __str__(self):\r\n    return \"I am \" + self.a + \", son of \" + Beta.super().__name__<\/pre>\n<p>D.<\/p>\n<pre class=\"lang:default decode:true \">def __str__(self):\r\n    return \"I am \" + self.a + \", son of \" + super().__name__<\/pre>\n<p>&nbsp;<\/p>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<div class=\"ud-component--base-components--code-block\">\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<p><strong>Explanation:<\/strong><\/p>\n<p><code>__str__()<\/code> is a method that allows to customize the string returned when printing an object.<\/p>\n<p>The expected output includes the name of the object being printed (in this case <code>beta<\/code>) and the name of its superclass (<code>Apha <\/code>in this case).<\/p>\n<p>For object <code>beta<\/code>, <code>beta.a<\/code> returns string <code>beta<\/code> &#8211; so\u00a0 <code>self.a<\/code> should be included in the <code>__str__()<\/code>\u00a0 method.<\/p>\n<p>String <code>Alpha<\/code>, can be returned using the property <code>__bases__<\/code> which is a tuple that includes the direct <strong>superclasses <\/strong>of a class. The first (and only) element in this tuple for class <code>Beta <\/code>is the class <code>Alpha<\/code>. Property <code>__name__<\/code> will return the name of a class. So : <code>Beta.__bases__[0].__name__<\/code>\u00a0 will return string <code>Alpha<\/code>.<\/p>\n<p>So, the correct answer is\u00a0 A<\/p>\n<p>The three other suggested answers will raise an exception.<\/p>\n<p dir=\"auto\">super() <strong>does not have<\/strong> an attribute called __name__.<\/p>\n<p>super() returns a <strong>proxy object<\/strong> that lets you call methods of the parent class.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Ex. 21<\/p>\n<div id=\"question-prompt\" class=\" ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>Which statement about Python classes is correct\u00a0 ?<\/p>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>A. <em>A class has a method named <code>__module__()<\/code> which returns the name of the module in which the class has been declared.<\/em><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-correct--PLOEU\" data-purpose=\"answer\">\n<div><span class=\"result-pane--answer-by-user-label--PSH86 ud-heading-xs\" data-purpose=\"answer-result-header-user-label\">B.\u00a0 <\/span><em>A class contains a property named <code>__name__<\/code> which stores the name of the class.<\/em><\/div>\n<div><\/div>\n<div>C. <em>A class contains a property named <code>__bases__<\/code> which is a tuple containing the name of the class&#8217;s superclasses.<\/em><\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-incorrect--vFyOv\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>&nbsp;<\/p>\n<p>D. <em>A class must have a constructor.<\/em><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>&nbsp;<\/p>\n<p><em>Explanation:<\/em><\/p>\n<p>Let &#8216;s review each suggested answers:<\/p>\n<p>&#8211;&gt;<em> A class must have a constructor.<\/em><\/p>\n<p>This is incorrect : a class can be defined without a constructor.<\/p>\n<p>&#8211;&gt; <strong><span style=\"color: #000000;\"><em>A class contains a property named <\/em><code><em>__name__<\/em><\/code><em> which stores the name of the class.<\/em><\/span><\/strong><\/p>\n<p><strong><span style=\"color: #000000;\">This is correct<\/span><\/strong><\/p>\n<p>&#8211;&gt; <em>A class contains a property named <\/em><code><em>__bases__<\/em><\/code><em> which is a tuple containing the name of the class&#8217;s superclasses.<\/em><\/p>\n<p>That is incorrect : this tuple contains the actual class&#8217;s superclasses, not their names.<\/p>\n<p>&#8211;&gt; <em>A class has a method named <\/em><code><em>__module__()<\/em><\/code><em> which returns the name of the module in which the class has been declared.<\/em><\/p>\n<p>That is incorrect : a class has a property named <code>__module__<\/code> (not a method) which returns the name of the module in which the class has been declared.<\/p>\n<p>Try it yourself:<\/p>\n<pre class=\"lang:default decode:true \">    class A:\r\n        # class does not have any constructor\r\n        pass\r\n     \r\n    class B(A):\r\n        # class does not have any constructor\r\n        pass\r\n     \r\n    print(B.__name__)    # B\r\n    print(B.__bases__)   # (&lt;class '__main__.A'&gt;,)\r\n    print(B.__module__)  # __main__<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Ex. 22<\/p>\n<p>Consider the code below :<\/p>\n<pre class=\"lang:default decode:true \">    class Alpha:\r\n        def __init__(self, val):\r\n            self.a = val\r\n     \r\n    class Beta(Alpha):\r\n        # insert code here\r\n     \r\n     \r\n    b = Beta(5,5)\r\n    print(b.a, b.b)<\/pre>\n<p>What code do you need to insert (in the class <code>Beta<\/code> definition), so that the output of the above code is:<\/p>\n<p><code>5 6<\/code><\/p>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-incorrect--vFyOv\" data-purpose=\"answer\">\n<div><span class=\"result-pane--answer-by-user-label--PSH86 ud-heading-xs\" data-purpose=\"answer-result-header-user-label\">A.<\/span><\/div>\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<pre class=\"lang:default decode:true\" style=\"padding-left: 40px;\">def __init__(self, x, y):\r\n  super().__init__(self, x)\r\n  self.b = y + 1<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-correct--PLOEU\" data-purpose=\"answer\">\n<div><span class=\"result-pane--answer-by-user-label--PSH86 ud-heading-xs\" data-purpose=\"answer-result-header-user-label\">B.<\/span><\/div>\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<pre class=\"lang:default decode:true \">def __init__(self, x, y):\r\n  super().__init__(x)\r\n  self.b = y + 1<\/pre>\n<p>C.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<pre class=\"lang:default decode:true\">def __init__(self, x, y):\r\n  Alpha.__init__(self, x)\r\n  self.b = y<\/pre>\n<p>D.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<pre class=\"lang:default decode:true\">def __init__(self, x, y):\r\n  Alpha.__init__(x)\r\n  self.b = y + 1<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-related-fields--c3m--\">\n<div class=\"overall-explanation-pane--overall-explanation--G-hLQ ud-form-group\">\n<div id=\"overall-explanation\" class=\"ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><em>Explanation:<\/em><\/p>\n<p><code>super()<\/code> returns a reference to the nearest superclass of the class. When used within a constructor, there is no need to pass the <code>self<\/code> argument to the method being invoked. So, in the above answer, <code>super().__init__(x)<\/code>\u00a0 will correctly invoke the <code>Alpha <\/code>constructor. An alternative would have been using the name of the super class explicitly as :<\/p>\n<p><code>Alpha.__init__(self, x)<\/code>\u00a0 (in this case the <code>self<\/code> argument must be passed to the constructor).<\/p>\n<p>Finally, to get <code>6<\/code> when printing <code>b.b<\/code>, we must have the following property definition in the Beta constructor :<\/p>\n<p><code>self.b = y + 1<\/code>.<\/p>\n<p><em>Try it yourself:<\/em><\/p>\n<pre class=\"lang:default decode:true\">    class Alpha:\r\n        def __init__(self, val):\r\n            self.a = val\r\n     \r\n    class Beta(Alpha):\r\n        def __init__(self, x, y):\r\n            super().__init__(x)\r\n            self.b = y + 1\r\n     \r\n    b = Beta(5,5)\r\n    print(b.a, b.b)    # 5 6\r\n<\/pre>\n<\/div>\n<p>B.<\/p>\n<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>1. A class is an idea (more or less abstract) which can be used to create a number of incarnations \u2013 such an incarnation is called an object.<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[100],"tags":[],"_links":{"self":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts\/6027"}],"collection":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/comments?post=6027"}],"version-history":[{"count":57,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts\/6027\/revisions"}],"predecessor-version":[{"id":6273,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts\/6027\/revisions\/6273"}],"wp:attachment":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/media?parent=6027"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/categories?post=6027"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/tags?post=6027"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}