.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/oop/class_methods.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code or to run this example in your browser via Binder .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_oop_class_methods.py: ==================== 3.10 class methods ==================== .. GENERATED FROM PYTHON SOURCE LINES 7-10 .. code-block:: default import datetime .. GENERATED FROM PYTHON SOURCE LINES 11-14 In previous section we saw that we can make a method linked to class by removing the keyword ``self`` from its input arguments and in this way we can call this method from class such as ``ClassName.MethodName()``. .. GENERATED FROM PYTHON SOURCE LINES 16-30 .. code-block:: default class Insan: __counter = 0 def __init__(self): type(self).__counter += 1 def PopulationCount(): return Insan.__counter Insan.PopulationCount() .. rst-class:: sphx-glr-script-out .. code-block:: none 0 .. GENERATED FROM PYTHON SOURCE LINES 31-33 Let's say, we also want to count male population, then we can add another static method as follows: .. GENERATED FROM PYTHON SOURCE LINES 35-61 .. code-block:: default class Insan: __counter = 0 __MaleCounter = 0 def __init__(self, gender): if gender == 'male': type(self).__MaleCounter += 1 type(self).__counter += 1 @staticmethod def PopulationCount(): return Insan.__counter @staticmethod def MaleCount(): return Insan.__MaleCounter ali = Insan('male') fatima = Insan('female') Insan.PopulationCount() .. rst-class:: sphx-glr-script-out .. code-block:: none 2 .. GENERATED FROM PYTHON SOURCE LINES 62-65 .. code-block:: default Insan.MaleCount() .. rst-class:: sphx-glr-script-out .. code-block:: none 1 .. GENERATED FROM PYTHON SOURCE LINES 66-68 If we want to now add female counter in above class, one way of doing it is to indirectly calculating it from total counter and male counter as follows .. GENERATED FROM PYTHON SOURCE LINES 70-97 .. code-block:: default class Insan: __counter = 0 __MaleCounter = 0 def __init__(self, gender): if gender == 'male': type(self).__MaleCounter += 1 type(self).__counter += 1 @staticmethod def PopulationCount(): return Insan.__counter @staticmethod def MaleCount(): return Insan.__MaleCounter def FemaleCount(): return Insan.__counter - Insan.__MaleCounter ali = Insan('male') fatima = Insan('female') .. GENERATED FROM PYTHON SOURCE LINES 98-101 .. code-block:: default print(Insan.PopulationCount()) .. rst-class:: sphx-glr-script-out .. code-block:: none 2 .. GENERATED FROM PYTHON SOURCE LINES 102-105 .. code-block:: default print(Insan.MaleCount()) .. rst-class:: sphx-glr-script-out .. code-block:: none 1 .. GENERATED FROM PYTHON SOURCE LINES 106-109 .. code-block:: default Insan.FemaleCount() .. rst-class:: sphx-glr-script-out .. code-block:: none 1 .. GENERATED FROM PYTHON SOURCE LINES 110-114 Another way of achieving this is to use the decorator ``@classmethod``. The use of this decorator makes sure that when we call this method, the first default implicit argument, that python provides to this method is the class itself. Thus we can make use of some static methods of the class without initializing the class .. GENERATED FROM PYTHON SOURCE LINES 116-147 .. code-block:: default class Insan: __counter = 0 __MaleCounter = 0 def __init__(self, gender): if gender == 'male': type(self).__MaleCounter += 1 type(self).__counter += 1 @staticmethod def PopulationCount(): return Insan.__counter @staticmethod def MaleCount(): return Insan.__MaleCounter @classmethod def FemaleCount(cls): return cls.__counter - cls.__MaleCounter ali = Insan('male') fatima = Insan('female') zeinab = Insan('female') print(Insan.PopulationCount()) .. rst-class:: sphx-glr-script-out .. code-block:: none 3 .. GENERATED FROM PYTHON SOURCE LINES 148-150 .. code-block:: default print(Insan.MaleCount()) .. rst-class:: sphx-glr-script-out .. code-block:: none 1 .. GENERATED FROM PYTHON SOURCE LINES 151-154 .. code-block:: default Insan.FemaleCount() .. rst-class:: sphx-glr-script-out .. code-block:: none 2 .. GENERATED FROM PYTHON SOURCE LINES 155-159 So until here class methods are behaving same as static methods in addition to that we can access other static methods of the class. It may not make a lot of sense but we will come to such use of class method once we cover ``inheritance``. Now Consider the following example: .. GENERATED FROM PYTHON SOURCE LINES 161-173 .. code-block:: default class Student(object): def __init__(self, name, age): self.name = name self.age = age ali = Student('ali', 12) print(type(ali)) .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 174-176 But let's say, for a particular student we don't know his/her age but we know the birth year. Thus we would like to build the class from birth year directly as well. .. GENERATED FROM PYTHON SOURCE LINES 178-196 .. code-block:: default class Student(object): def __init__(self, name, age): self.name = name self.age = age @classmethod def fromBirthYear(cls, name, BirthYear): current_year = datetime.date.today().year age = current_year - BirthYear return cls(name, age) ali = Student('ali', 12) print(type(ali)) .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 197-201 .. code-block:: default hasan = Student.fromBirthYear('hasan', 1997) print(type(hasan)) .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 202-205 .. code-block:: default print(hasan.age) .. rst-class:: sphx-glr-script-out .. code-block:: none 27 .. GENERATED FROM PYTHON SOURCE LINES 206-210 Thus we used the ``class method`` to build/initiate the class from birth year. We could have performed the conversion of ``BirthYear`` to ``age`` outside the class as well but this way provides a more user friendly interface of the class and the code is more organized. .. rst-class:: sphx-glr-timing **Total running time of the script:** ( 0 minutes 0.006 seconds) .. _sphx_glr_download_auto_examples_oop_class_methods.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/AtrCheema/python-seekho/master?urlpath=lab/tree/notebooks/auto_examples/oop/class_methods.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: class_methods.py ` .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: class_methods.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_