{"id":2588,"date":"2021-10-19T03:10:29","date_gmt":"2021-10-19T03:10:29","guid":{"rendered":"https:\/\/www.pythontutorial.net\/?page_id=2588"},"modified":"2025-03-31T10:08:45","modified_gmt":"2025-03-31T10:08:45","slug":"python-operator-overloading","status":"publish","type":"page","link":"https:\/\/www.pythontutorial.net\/python-oop\/python-operator-overloading\/","title":{"rendered":"Python Operator Overloading"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn Python operator overloading and how to use it to make your objects work with built-in operators.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='introduction-to-the-python-operator-overloading'>Introduction to the Python operator overloading <a href=\"#introduction-to-the-python-operator-overloading\" class=\"anchor\" id=\"introduction-to-the-python-operator-overloading\" title=\"Anchor for Introduction to the Python operator overloading\">#<\/a><\/h2>\n\n\n\n<p>Suppose you have a 2D point <a href=\"https:\/\/www.pythontutorial.net\/python-oop\/python-class\/\">class<\/a> with x and y coordinate <a href=\"https:\/\/www.pythontutorial.net\/python-oop\/python-instance-variables\/\">attributes<\/a>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Point2D<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, x, y)<\/span>:<\/span>\n        self.x = x\n        self.y = y\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__str__<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-string\">f'(<span class=\"hljs-subst\">{self.x}<\/span>,<span class=\"hljs-subst\">{self.y}<\/span>)'<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>To add two <code>Point2D<\/code> objects, you can define an <code>add()<\/code> method as follows:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Point2D<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, x, y)<\/span>:<\/span>\n        self.x = x\n        self.y = y\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__str__<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-string\">f'(<span class=\"hljs-subst\">{self.x}<\/span>,<span class=\"hljs-subst\">{self.y}<\/span>)'<\/span>\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">add<\/span><span class=\"hljs-params\">(self, point)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">if<\/span> <span class=\"hljs-keyword\">not<\/span> isinstance(point, Point2D):\n            <span class=\"hljs-keyword\">raise<\/span> ValueError(<span class=\"hljs-string\">'The other must be an instance of the Point2D'<\/span>)\n\n        <span class=\"hljs-keyword\">return<\/span> Point2D(self.x + point.x, self.y + point.y)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>add()<\/code> method raises an error if the point is not an instance of the <code>Point2D<\/code> class. Otherwise, it returns a new <code>Point2D<\/code> object whose x and y coordinates are the sums of <code>x<\/code> and <code>y<\/code> coordinates of two points.<\/p>\n\n\n\n<p>The following creates two instances of the <code>Point2D<\/code> class and use the <code>add()<\/code> method to add two points:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Point2D<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, x, y)<\/span>:<\/span>\n        self.x = x\n        self.y = y\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__str__<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-string\">f'(<span class=\"hljs-subst\">{self.x}<\/span>,<span class=\"hljs-subst\">{self.y}<\/span>)'<\/span>\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">add<\/span><span class=\"hljs-params\">(self, point)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">if<\/span> <span class=\"hljs-keyword\">not<\/span> isinstance(point, Point2D):\n            <span class=\"hljs-keyword\">raise<\/span> ValueError(<span class=\"hljs-string\">'The other must be an instance of the Point2D'<\/span>)\n\n        <span class=\"hljs-keyword\">return<\/span> Point2D(self.x + point.x, self.y + point.y)\n\na = Point2D(<span class=\"hljs-number\">10<\/span>, <span class=\"hljs-number\">20<\/span>)\nb = Point2D(<span class=\"hljs-number\">15<\/span>, <span class=\"hljs-number\">25<\/span>)\nc = a.add(b)\n\nprint(c)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pythontutorial.net\/playground\/?q=Y2xhc3MgUG9pbnQyRDoKICAgIGRlZiBfX2luaXRfXyhzZWxmLCB4LCB5KToKICAgICAgICBzZWxmLnggPSB4CiAgICAgICAgc2VsZi55ID0geQoKICAgIGRlZiBfX3N0cl9fKHNlbGYpOgogICAgICAgIHJldHVybiBmJyh7c2VsZi54fSx7c2VsZi55fSknCgogICAgZGVmIGFkZChzZWxmLCBwb2ludCk6CiAgICAgICAgaWYgbm90IGlzaW5zdGFuY2UocG9pbnQsIFBvaW50MkQpOgogICAgICAgICAgICByYWlzZSBWYWx1ZUVycm9yKCdUaGUgb3RoZXIgbXVzdCBiZSBhbiBpbnN0YW5jZSBvZiB0aGUgUG9pbnQyRCcpCgogICAgICAgIHJldHVybiBQb2ludDJEKHNlbGYueCArIHBvaW50LngsIHNlbGYueSArIHBvaW50LnkpCgphID0gUG9pbnQyRCgxMCwgMjApCmIgPSBQb2ludDJEKDE1LCAyNSkKYyA9IGEuYWRkKGIpCgpwcmludChjKQ%3D%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">(<span class=\"hljs-number\">25<\/span>,<span class=\"hljs-number\">45<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>This code works perfectly fine. But Python has a better way to implement it. Instead of using the <code>add()<\/code> method, you can use the built-in operator (+) like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">c = a + b<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>When you use the <code>+<\/code> operator on the <code>Point2D<\/code> object, Python will call the special method <code>__add__()<\/code> on the object. The following calls are equivalent:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">c = a + b\nc = a.__add__(b)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>__add__()<\/code> method must return a new instance of the <code>Point2D<\/code> object.<\/p>\n\n\n\n<p>The ability to use the built-in operator (<code>+<\/code>) on a custom type is known as operator overloading.<\/p>\n\n\n\n<p>The following shows the <code>Point2D<\/code> class that implements the <code>__add__()<\/code> special operator to support the <code>+<\/code> operator:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Point2D<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, x, y)<\/span>:<\/span>\n        self.x = x\n        self.y = y\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__str__<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-string\">f'(<span class=\"hljs-subst\">{self.x}<\/span>,<span class=\"hljs-subst\">{self.y}<\/span>)'<\/span>\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__add__<\/span><span class=\"hljs-params\">(self, point)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">if<\/span> <span class=\"hljs-keyword\">not<\/span> isinstance(point, Point2D):\n            <span class=\"hljs-keyword\">raise<\/span> ValueError(<span class=\"hljs-string\">'The other must be an instance of the Point2D'<\/span>)\n\n        <span class=\"hljs-keyword\">return<\/span> Point2D(self.x + point.x, self.y + point.y)\n\n\na = Point2D(<span class=\"hljs-number\">10<\/span>, <span class=\"hljs-number\">20<\/span>)\nb = Point2D(<span class=\"hljs-number\">15<\/span>, <span class=\"hljs-number\">25<\/span>)\nc = a + b\nprint(c)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pythontutorial.net\/playground\/?q=Y2xhc3MgUG9pbnQyRDoKICAgIGRlZiBfX2luaXRfXyhzZWxmLCB4LCB5KToKICAgICAgICBzZWxmLnggPSB4CiAgICAgICAgc2VsZi55ID0geQoKICAgIGRlZiBfX3N0cl9fKHNlbGYpOgogICAgICAgIHJldHVybiBmJyh7c2VsZi54fSx7c2VsZi55fSknCgogICAgZGVmIF9fYWRkX18oc2VsZiwgcG9pbnQpOgogICAgICAgIGlmIG5vdCBpc2luc3RhbmNlKHBvaW50LCBQb2ludDJEKToKICAgICAgICAgICAgcmFpc2UgVmFsdWVFcnJvcignVGhlIG90aGVyIG11c3QgYmUgYW4gaW5zdGFuY2Ugb2YgdGhlIFBvaW50MkQnKQoKICAgICAgICByZXR1cm4gUG9pbnQyRChzZWxmLnggKyBwb2ludC54LCBzZWxmLnkgKyBwb2ludC55KQoKCmEgPSBQb2ludDJEKDEwLCAyMCkKYiA9IFBvaW50MkQoMTUsIDI1KQpjID0gYSArIGIKcHJpbnQoYyk%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">(25,45)<\/code><\/span><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='special-methods-for-operator-overloading'>Special methods for operator overloading <a href=\"#special-methods-for-operator-overloading\" class=\"anchor\" id=\"special-methods-for-operator-overloading\" title=\"Anchor for Special methods for operator overloading\">#<\/a><\/h2>\n\n\n\n<p>The following shows the operators with their corresponding special methods:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Operator<\/th><th>Special Methods<\/th><\/tr><\/thead><tbody><tr><td>+<\/td><td>__add__(self, other)<\/td><\/tr><tr><td>&#8211;<\/td><td>__sub__(self, other)<\/td><\/tr><tr><td>*<\/td><td> __mul__(self, other) <\/td><\/tr><tr><td>\/<\/td><td> __truediv__(self, other) <\/td><\/tr><tr><td>\/\/<\/td><td> __floordiv__(self, other) <\/td><\/tr><tr><td>%<\/td><td> __mod__(self, other) <\/td><\/tr><tr><td>**<\/td><td> __pow__(self, other) <\/td><\/tr><tr><td>&gt;&gt;<\/td><td> __rshift__(self, other) <\/td><\/tr><tr><td>&lt;&lt;<\/td><td> __lshift__(self, other) <\/td><\/tr><tr><td>&amp;<\/td><td>  __and__(self, other) <\/td><\/tr><tr><td>|<\/td><td> __or__(self, other) <\/td><\/tr><tr><td>^<\/td><td> __xor__(self, other) <\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>For example, you can implement the <code>__sub__()<\/code> method in the Point2D to support subtraction (<code>-<\/code>) of two points:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Point2D<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, x, y)<\/span>:<\/span>\n        self.x = x\n        self.y = y\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__str__<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-string\">f'(<span class=\"hljs-subst\">{self.x}<\/span>,<span class=\"hljs-subst\">{self.y}<\/span>)'<\/span>\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__add__<\/span><span class=\"hljs-params\">(self, point)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">if<\/span> <span class=\"hljs-keyword\">not<\/span> isinstance(point, Point2D):\n            <span class=\"hljs-keyword\">raise<\/span> ValueError(<span class=\"hljs-string\">'The other must be an instance of the Point2D'<\/span>)\n\n        <span class=\"hljs-keyword\">return<\/span> Point2D(self.x + point.x, self.y + point.y)\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__sub__<\/span><span class=\"hljs-params\">(self, other)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">if<\/span> <span class=\"hljs-keyword\">not<\/span> isinstance(other, Point2D):\n            <span class=\"hljs-keyword\">raise<\/span> ValueError(<span class=\"hljs-string\">'The other must be an instance of the Point2D'<\/span>)\n\n        <span class=\"hljs-keyword\">return<\/span> Point2D(self.x - other.x, self.y - other.y)\n\n\n<span class=\"hljs-keyword\">if<\/span> __name__ == <span class=\"hljs-string\">'__main__'<\/span>:\n    a = Point2D(<span class=\"hljs-number\">10<\/span>, <span class=\"hljs-number\">20<\/span>)\n    b = Point2D(<span class=\"hljs-number\">15<\/span>, <span class=\"hljs-number\">25<\/span>)\n    c = b - a\n    print(c)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='overloading-inplace-operators'>Overloading inplace operators <a href=\"#overloading-inplace-operators\" class=\"anchor\" id=\"overloading-inplace-operators\" title=\"Anchor for Overloading inplace operators\">#<\/a><\/h2>\n\n\n\n<p>Some operators have the inplace version. For example, the inplace version of + is +=.<\/p>\n\n\n\n<p>For the immutable type like a <a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-tuples\/\">tuple<\/a>, a string, a number, the inplace operators perform calculations and don&#8217;t assign the result back to the input object.<\/p>\n\n\n\n<p>For the mutable type, the inplace operator performs the updates on the original objects directly. The assignment is not necessary.<\/p>\n\n\n\n<p>Python also provides you with a list of special methods that allows you to overload the inplace operator:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Operator<\/th><th>Special Method<\/th><\/tr><\/thead><tbody><tr><td>+=<\/td><td>__iadd__(self, other)<\/td><\/tr><tr><td>-=<\/td><td>__isub__(self, other)<\/td><\/tr><tr><td>*=<\/td><td> __imul__(self, other) <\/td><\/tr><tr><td>\/=<\/td><td> __itruediv__(self, other) <\/td><\/tr><tr><td>\/\/=<\/td><td> __ifloordiv__(self, other) <\/td><\/tr><tr><td>%=<\/td><td> __imod__(self, other) <\/td><\/tr><tr><td>**=<\/td><td> __ipow__(self, other) <\/td><\/tr><tr><td>&gt;&gt;=<\/td><td> __irshift__(self, other) <\/td><\/tr><tr><td>&lt;&lt;=<\/td><td> __ilshift__(self, other) <\/td><\/tr><tr><td>&amp;=<\/td><td>  __iand__(self, other) <\/td><\/tr><tr><td>|=<\/td><td> __ior__(self, other) <\/td><\/tr><tr><td>^=<\/td><td> __ixor__(self, other) <\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Let&#8217;s take an example of overloading the <code>+=<\/code> operator.<\/p>\n\n\n\n<p>Suppose you have a cart object and you want to add an item to the cart. To do you, you can define an <code>add()<\/code> method to the <code>Cart<\/code> class and use it like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">cart.add(item)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Alternatively, you can implement the <code>+=<\/code> operator in the <code>Cart<\/code> class. It allows you to add an item to the cart as follows:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">cart += item<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>To support the += operator, you need to implement the <code>__iadd__<\/code> special method in the <code>Cart<\/code> class.<\/p>\n\n\n\n<p>First, define the <code>Item<\/code> class that has three attributes name, quantity, and price. Also, it has an amount property that returns the subtotal of the item:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Item<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, name, qty, price)<\/span>:<\/span>\n        self.name = name\n        self.qty = qty\n        self.price = price\n\n<span class=\"hljs-meta\">    @property<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">amount<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> self.qty * self.price\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__str__<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-string\">f'<span class=\"hljs-subst\">{self.name}<\/span> <span class=\"hljs-subst\">{self.qty}<\/span> $<span class=\"hljs-subst\">{self.price}<\/span> $<span class=\"hljs-subst\">{self.amount}<\/span>'<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Second, define the <code>Cart<\/code> class that implements the <code>__iadd__<\/code> method:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Cart<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        self.items = &#91;]\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__iadd__<\/span><span class=\"hljs-params\">(self, item)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">if<\/span> <span class=\"hljs-keyword\">not<\/span> isinstance(item, Item):\n            <span class=\"hljs-keyword\">raise<\/span> ValueError(<span class=\"hljs-string\">'The item must be an instance of Item'<\/span>)\n\n        self.items.append(item)\n        <span class=\"hljs-keyword\">return<\/span> self\n\n<span class=\"hljs-meta\">    @property<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">total<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> sum(&#91;item.amount <span class=\"hljs-keyword\">for<\/span> item <span class=\"hljs-keyword\">in<\/span> self.items])\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__str__<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">if<\/span> <span class=\"hljs-keyword\">not<\/span> self.items:\n            <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-string\">'The cart is empty'<\/span>\n\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-string\">'\\n'<\/span>.join(&#91;str(item) <span class=\"hljs-keyword\">for<\/span> item <span class=\"hljs-keyword\">in<\/span> self.items])<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In the <code>__iadd__<\/code> method, we raise a <code>ValueError<\/code> if the item is not an instance of the <code>Item<\/code> class. Otherwise, we add the item to the items list attribute.<\/p>\n\n\n\n<p>The total property returns the sum of all items.<\/p>\n\n\n\n<p>The <code>__str__<\/code> method returns the string <code>'The cart is empty'<\/code> if the cart has no item. Otherwise, it returns a string that contains all items separated by a newline.<\/p>\n\n\n\n<p>Third, use the <code>+=<\/code> operator to add an item to the cart:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Item<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, name, qty, price)<\/span>:<\/span>\n        self.name = name\n        self.qty = qty\n        self.price = price\n\n<span class=\"hljs-meta\">    @property<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">amount<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> self.qty * self.price\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__str__<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-string\">f'<span class=\"hljs-subst\">{self.name}<\/span> <span class=\"hljs-subst\">{self.qty}<\/span> $<span class=\"hljs-subst\">{self.price}<\/span> $<span class=\"hljs-subst\">{self.amount}<\/span>'<\/span>\n    \n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Cart<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        self.items = &#91;]\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__iadd__<\/span><span class=\"hljs-params\">(self, item)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">if<\/span> <span class=\"hljs-keyword\">not<\/span> isinstance(item, Item):\n            <span class=\"hljs-keyword\">raise<\/span> ValueError(<span class=\"hljs-string\">'The item must be an instance of Item'<\/span>)\n\n        self.items.append(item)\n        <span class=\"hljs-keyword\">return<\/span> self\n\n<span class=\"hljs-meta\">    @property<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">total<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> sum(&#91;item.amount <span class=\"hljs-keyword\">for<\/span> item <span class=\"hljs-keyword\">in<\/span> self.items])\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__str__<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">if<\/span> <span class=\"hljs-keyword\">not<\/span> self.items:\n            <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-string\">'The cart is empty'<\/span>\n\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-string\">'\\n'<\/span>.join(&#91;str(item) <span class=\"hljs-keyword\">for<\/span> item <span class=\"hljs-keyword\">in<\/span> self.items])\n\ncart = Cart()\n\ncart += Item(<span class=\"hljs-string\">'Apple'<\/span>, <span class=\"hljs-number\">5<\/span>, <span class=\"hljs-number\">2<\/span>)\ncart += Item(<span class=\"hljs-string\">'Banana'<\/span>, <span class=\"hljs-number\">20<\/span>, <span class=\"hljs-number\">1<\/span>)\ncart += Item(<span class=\"hljs-string\">'Orange'<\/span>, <span class=\"hljs-number\">10<\/span>, <span class=\"hljs-number\">1.5<\/span>)\n\nprint(cart)\n<span class=\"hljs-comment\"># print the total line<\/span>\nprint(<span class=\"hljs-string\">'-'<\/span> * <span class=\"hljs-number\">30<\/span>)\nprint(<span class=\"hljs-string\">'Total: $'<\/span>, cart.total)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pythontutorial.net\/playground\/?q=Y2xhc3MgSXRlbToKICAgIGRlZiBfX2luaXRfXyhzZWxmLCBuYW1lLCBxdHksIHByaWNlKToKICAgICAgICBzZWxmLm5hbWUgPSBuYW1lCiAgICAgICAgc2VsZi5xdHkgPSBxdHkKICAgICAgICBzZWxmLnByaWNlID0gcHJpY2UKCiAgICBAcHJvcGVydHkKICAgIGRlZiBhbW91bnQoc2VsZik6CiAgICAgICAgcmV0dXJuIHNlbGYucXR5ICogc2VsZi5wcmljZQoKICAgIGRlZiBfX3N0cl9fKHNlbGYpOgogICAgICAgIHJldHVybiBmJ3tzZWxmLm5hbWV9IHtzZWxmLnF0eX0gJHtzZWxmLnByaWNlfSAke3NlbGYuYW1vdW50fScKICAgIApjbGFzcyBDYXJ0OgogICAgZGVmIF9faW5pdF9fKHNlbGYpOgogICAgICAgIHNlbGYuaXRlbXMgPSBbXQoKICAgIGRlZiBfX2lhZGRfXyhzZWxmLCBpdGVtKToKICAgICAgICBpZiBub3QgaXNpbnN0YW5jZShpdGVtLCBJdGVtKToKICAgICAgICAgICAgcmFpc2UgVmFsdWVFcnJvcignVGhlIGl0ZW0gbXVzdCBiZSBhbiBpbnN0YW5jZSBvZiBJdGVtJykKCiAgICAgICAgc2VsZi5pdGVtcy5hcHBlbmQoaXRlbSkKICAgICAgICByZXR1cm4gc2VsZgoKICAgIEBwcm9wZXJ0eQogICAgZGVmIHRvdGFsKHNlbGYpOgogICAgICAgIHJldHVybiBzdW0oW2l0ZW0uYW1vdW50IGZvciBpdGVtIGluIHNlbGYuaXRlbXNdKQoKICAgIGRlZiBfX3N0cl9fKHNlbGYpOgogICAgICAgIGlmIG5vdCBzZWxmLml0ZW1zOgogICAgICAgICAgICByZXR1cm4gJ1RoZSBjYXJ0IGlzIGVtcHR5JwoKICAgICAgICByZXR1cm4gJ1xuJy5qb2luKFtzdHIoaXRlbSkgZm9yIGl0ZW0gaW4gc2VsZi5pdGVtc10pCgpjYXJ0ID0gQ2FydCgpCgpjYXJ0ICs9IEl0ZW0oJ0FwcGxlJywgNSwgMikKY2FydCArPSBJdGVtKCdCYW5hbmEnLCAyMCwgMSkKY2FydCArPSBJdGVtKCdPcmFuZ2UnLCAxMCwgMS41KQoKcHJpbnQoY2FydCkKIyBwcmludCB0aGUgdG90YWwgbGluZQpwcmludCgnLScgKiAzMCkKcHJpbnQoJ1RvdGFsOiAkJywgY2FydC50b3RhbCk%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-14\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">Apple   <span class=\"hljs-number\">5<\/span>       $<span class=\"hljs-number\">2<\/span>      $<span class=\"hljs-number\">10<\/span>\nBanana  <span class=\"hljs-number\">20<\/span>      $<span class=\"hljs-number\">1<\/span>      $<span class=\"hljs-number\">20<\/span>\nOrange  <span class=\"hljs-number\">10<\/span>      $<span class=\"hljs-number\">1.5<\/span>    $<span class=\"hljs-number\">15.0<\/span>\n------------------------------\nTotal: $ <span class=\"hljs-number\">45.0<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-14\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='summary'>Summary <a href=\"#summary\" class=\"anchor\" id=\"summary\" title=\"Anchor for Summary\">#<\/a><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Operator overloading allows a class to use built-in operators.<\/li>\n<\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"2588\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-oop\/python-operator-overloading\/\"\n\t\t\t\tdata-post-title=\"Python Operator Overloading\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"2588\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-oop\/python-operator-overloading\/\"\n\t\t\t\tdata-post-title=\"Python Operator Overloading\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\t\t\t<input type=\"button\" name=\"wth-submit\" class=\"wth-btn wth-btn-submit\" id=\"wth-submit\" \/>\n\t\t\t<input type=\"button\" class=\"wth-btn wth-btn-cancel\" value=\"Cancel\" \/>\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll learn Python operator overloading and how to use it to make your objects work with built-in operators.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":417,"menu_order":16,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-2588","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/2588","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/comments?post=2588"}],"version-history":[{"count":2,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/2588\/revisions"}],"predecessor-version":[{"id":7308,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/2588\/revisions\/7308"}],"up":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/417"}],"wp:attachment":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/media?parent=2588"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}