Created
May 26, 2019 21:10
-
-
Save simecek/b00f0df694c6318130cfeaf1586dca3f to your computer and use it in GitHub Desktop.
Number Of instances.ipynb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"nbformat": 4, | |
"nbformat_minor": 0, | |
"metadata": { | |
"colab": { | |
"name": "Number Of instances.ipynb", | |
"version": "0.3.2", | |
"provenance": [], | |
"include_colab_link": true | |
}, | |
"kernelspec": { | |
"name": "python3", | |
"display_name": "Python 3" | |
} | |
}, | |
"cells": [ | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"id": "view-in-github", | |
"colab_type": "text" | |
}, | |
"source": [ | |
"<a href=\"https://colab.research.google.com/gist/simecek/b00f0df694c6318130cfeaf1586dca3f/number-of-instances.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"metadata": { | |
"id": "Bd7ia1vf-9co", | |
"colab_type": "code", | |
"colab": { | |
"base_uri": "https://localhost:8080/", | |
"height": 35 | |
}, | |
"outputId": "1c7b3bdb-4eec-4a19-ef54-17f92f7a4b9f" | |
}, | |
"source": [ | |
"# This counter does not work\n", | |
"\n", | |
"class Foo:\n", | |
" _num_instances = 0\n", | |
" def __init__(self):\n", | |
" self._num_instances += 1\n", | |
" \n", | |
"f1 = Foo()\n", | |
"f2 = Foo()\n", | |
"print(Foo._num_instances)" | |
], | |
"execution_count": 1, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"text": [ | |
"0\n" | |
], | |
"name": "stdout" | |
} | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"metadata": { | |
"id": "G4G94xcm9jmJ", | |
"colab_type": "code", | |
"colab": { | |
"base_uri": "https://localhost:8080/", | |
"height": 35 | |
}, | |
"outputId": "53f47d3b-1b6a-4644-cf04-fd27e93216ad" | |
}, | |
"source": [ | |
"# This counter works thanks to @classmethod\n", | |
"\n", | |
"class Foo: \n", | |
" _num_instances = 0\n", | |
" @classmethod\n", | |
" def create(cls):\n", | |
" instance = cls()\n", | |
" cls._num_instances += 1\n", | |
" return instance\n", | |
" \n", | |
"f1 = Foo.create()\n", | |
"f2 = Foo.create()\n", | |
"print(Foo._num_instances)" | |
], | |
"execution_count": 2, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"text": [ | |
"2\n" | |
], | |
"name": "stdout" | |
} | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"metadata": { | |
"id": "Fxwao0RC902L", | |
"colab_type": "code", | |
"colab": {} | |
}, | |
"source": [ | |
"" | |
], | |
"execution_count": 0, | |
"outputs": [] | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment