{"id":26137875,"url":"https://github.com/rampal-punia/python-class-tutorial","last_synced_at":"2025-10-11T08:35:20.083Z","repository":{"id":89201280,"uuid":"552357558","full_name":"rampal-punia/python-class-tutorial","owner":"rampal-punia","description":"Python OOP tutorial with three examples(Point class, Animal Class and Rectangle Class) \u0026 one project (Student Management System)","archived":false,"fork":false,"pushed_at":"2022-12-07T15:54:35.000Z","size":54,"stargazers_count":7,"open_issues_count":0,"forks_count":2,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-13T23:14:39.260Z","etag":null,"topics":["class","classes-and-objects","classes-in-python","inheritance-examples","object-oriented-programming","oop","python","python-classes","python-objects"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rampal-punia.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-10-16T12:14:04.000Z","updated_at":"2024-11-03T14:28:15.000Z","dependencies_parsed_at":"2023-06-14T10:00:33.401Z","dependency_job_id":null,"html_url":"https://github.com/rampal-punia/python-class-tutorial","commit_stats":null,"previous_names":["rampal-punia/python-class-tutorial"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/rampal-punia/python-class-tutorial","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rampal-punia%2Fpython-class-tutorial","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rampal-punia%2Fpython-class-tutorial/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rampal-punia%2Fpython-class-tutorial/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rampal-punia%2Fpython-class-tutorial/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rampal-punia","download_url":"https://codeload.github.com/rampal-punia/python-class-tutorial/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rampal-punia%2Fpython-class-tutorial/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279006610,"owners_count":26084148,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-11T02:00:06.511Z","response_time":55,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["class","classes-and-objects","classes-in-python","inheritance-examples","object-oriented-programming","oop","python","python-classes","python-objects"],"created_at":"2025-03-11T01:08:43.912Z","updated_at":"2025-10-11T08:35:20.046Z","avatar_url":"https://github.com/rampal-punia.png","language":"Python","readme":"# Python Classes Tutorial\n\nIf we look at the features of the Python Programming Language. We find that, Python is/has:\n\n- Easy to learn\n\n- Powerful \u0026 interpreted programming language\n\n- Ideal for scripting and rapid application development\n\n- Efficient high-level data structures\n\n- Effective approach to object-oriented programming\n\n- Elegant syntax and dynamic typing\n\n- Useful in various domains on most platforms\n\nOne of the main features of Python is; it has **Effective approach to object-oriented programming**. So, let's first find out what does `Object-Oriented-Programming` means?\n\nOOP is the programming paradigm where the real-life object is at the center of all the concepts and methodology used to perform a task or a process. Instead of calling the procedures and functions to calculate the data as and when required, OOP uses a blueprint to create an object of a class and bundle data and functionality to it.\n\nEverything in Python is an object. They have some data and functionality associated with them. So all the Python objects like **list**, **int**, **str**, **tuple**, **functions**, **sys** etc are objects.\n\n---\n\n## In this tutorial:\n\n- [Definition of a 'class'](https://github.com/CodingMantras/python-class-tutorial#definition-of-class)\n\n- [Reason for creating a class](https://github.com/CodingMantras/python-class-tutorial#reason-for-creating-a-class)\n\n- [`class` keyword and `__init__` method](https://github.com/CodingMantras/python-class-tutorial#class-keyword-and-init-method)\n\n- [Naming a 'class'](https://github.com/CodingMantras/python-class-tutorial#naming-a-class)\n\n- [Instance of a class](https://github.com/CodingMantras/python-class-tutorial#instance)\n\n- [Attributes \u0026 Methods](https://github.com/CodingMantras/python-class-tutorial#attributes-and-methods)\n\n- [Instance variables and class variables](https://github.com/CodingMantras/python-class-tutorial#instance-variables-and-class-variables)\n\n- [Instance methods, class methods and static methods](https://github.com/CodingMantras/python-class-tutorial#instance-methods-class-methods-and-static-methods)\n\n- [Helpful in-build methods: `dir()`, `help(__class__)`, `MRO`, `is_instance` and  `__dict__`.](https://github.com/CodingMantras/python-class-tutorial#helpful-in-build-methods)\n\n- Use of property decorator\n\n- [OOPs concepts (Inheritance, Polymorphism, Encapsulation, Abstraction - IPEA)](https://github.com/CodingMantras/python-class-tutorial#oops-concepts)\n\n---\n\n## Examples and Project (Tutorials Purpose):\n\n1. [Point Class](https://github.com/CodingMantras/python-class-tutorial/blob/master/examples/1_point_class.py)\n\n2. [Animal Class](https://github.com/CodingMantras/python-class-tutorial/blob/master/examples/2_2_animal_class.py)\n\n3. [Rectangle Class](https://github.com/CodingMantras/python-class-tutorial/blob/master/examples/3_2_rectangle_class.py)\n\n4. [Student Management System](https://github.com/CodingMantras/python-class-tutorial/blob/master/school_management/main.py)\n\n---\n\n## Definition of class:\n\nA python class is like a **blueprint to create a new object**. The objects having similar set of attributes and behaviors goes to the same class. For example: Cars, TV, Employees, Students, Smart phones. All the new objects of a class shares similar attributes and methods.\n\n---\n\n## Reason for creating a class:\nTo accumulate the data and functionalities of similar objects at one place. \n\nBy creating a new object we add this new instance, or any future instance, to a particular bundle. That bundle is called a `class`. If we have the same set of objects with similar attributes and functionalities we should create a class. Also, class supports inheritance. With classes we can reuse our codes or the codes written by other programmers. (Packages, modules and frameworks)\n\nThe state of objects of a class should be changed through the methods defined in the class. The whole point of creating a class is to put the codes that can change the state of a class at the same place, nice and organized, so that we know where to find in the code base to fix a related bug. Classes not only increase the readability and the reusability of the code but also the maintainability.\n\nWith proper implementation of classes, in theories, we achieve:\n\n- Separation of concerns\n\n- Decoupling\n\n- Encapsulation\n\n- Implementation hiding\n\n- Inheritance\n\n---\n\n## Naming a class\n\nTo name a `class` in Python the convention is to start with capital letter like: Animal, Employee. Similarly if the class is made up with two or more words, each word has the first letter capitalize like: ImageDetector, PointRotationCalculator etc.\n\n---\n\n## class keyword and __init__ method\nTo create a user defined object we use **class** keyword in Python. The special method **__init__** is used to initialize an object of that class.\n\nLet's look at an example of creating a user defined class in Python.\n\n### An example of a `Car class`:\nLet's say, we need to create a record of cars manufactured by the Tata Motors. The data and data related to car are as mentioned below. \n\nMAKE = \"TATA Motors\"\nYear = 2022\n\n|Model|Category|Speed|\n|-----|---|---|\n|Altroz|Hatchback|160|\n|Nexon|Compack SUV|160|\n|Harrier|SUV|180|\n|Safari|MUV|170|\n\n**A table containing details of each Car. The row of this table represents the each instance of a class and columns represents attributes associated with an instance of the Car class**. \n\nFor this we will create the Car class in Python like below:\n\n```python\nclass Car:\n    \"\"\"A car class for all the models of a car company.\"\"\"\n    MAKE = \"TATA Motors\"\n    year = 2022\n\n    def __init__(self, model, category, speed):\n        \"\"\"Constructor of Car class with model, category and speed.\n\n        Args:\n            model (str): the model of the car\n            category (str): name of the category of the car\n            speed (int): The speed of the car\n        \"\"\"\n        self.model = model\n        self.category = category\n        self.speed = speed\n\n    def get_speed(self):\n        return f\"The max-speed of {Car.MAKE} car '{self.model}' is {self.speed} km/h\"\n\n    def accelerate(self):\n        return \"The vehicle is accelerating\"\n\n    def apply_brake(self):\n        return \"The vehicle is de-accelerating\"\n\n    def description(self):\n        print(\"==========================================\")\n        print(f\"Company name: {Car.MAKE}\")\n        print(f\"Model: {self.model}\")\n        print(f\"Category: {self.category}\")\n        print(f\"Max Speed: {self.speed}\")\n        print(f\"Manufacturing Year: {Car.year}\")\n        print()\n\n    @classmethod\n    def change_year(cls, new_year):\n        cls.year = new_year\n        return cls.year\n\n\ncar1 = Car(\"Altroz\", \"Hatchback\", 160)\ncar2 = Car(\"Nexon\", \"Compact SUV\", 160)\ncar3 = Car(\"Safari\", \"MUV\", 170)\ncar4 = Car(\"Harrier\", \"SUV\", 180)\ncar1.description()\ncar2.description()\ncar3.description()\ncar4.description()\n```\n\n---\n\n## Instance\nAn object of a class (constructed or instantiated from the class) is called the instance of that class. From our car class example (above):\n\nIf we want to add another record into our Car table above, so we will **create new instance of the car class**, it means we already have 4 instances(rows) in our table, and now let's create the fifth one.\n\n---\n\n## Attributes and methods:\nFrom the above example of a Car class we can deduce:\n\n- Attributes: model, category, speed\n- Methods: get_speed(), accelerate(), apply_break(), description().\n\n---\n\n## Instance variables and class variables\n\n### Instance variables:\nThe variables associated to a particular instance of a class.Also we can say, the variables created when an object of a class is instantiated are called instance variables. These variables are not shared by the objects they are specific to a particular objects. \n\nWe can declared them in the special method of a class named **__init__**.\n\nIn our example of Car class, every instance of the Car class have their own set of model, category, speed associated with it. So, these are the instance variables(attributes)\n\nWe use dot notation with class instance  to access them. e.g.\n```python\n# create a new instance\ncar1 = Car(\"Harrier\", \"grey\", 180)\n\n# access the name and speed of this instance\nprint(car.name)\nprint(car.speed)\n```\n\n### Class variables:\nThe variables associated with all the the instances of a class. They are shared by all the instances of that class.\n\nwe can declare them within a class but outside of any method.\n\nIn our example of Car class, the MAKE and year are the same for all the Cars for a particular year. So we declare them **outside of the __init__** method.\n\n```python\nclass Car:\n    MAKE = \"TATA Motors\"\n    year = 2022\n```\n\nWe use dot notation with class name to access class variables. e.g.\n```python\n# access the class variables\nprint(Car.MAKE)\nprint(Car.year)\n```\n---\n\n## Instance methods class methods, and static methods\n\n### Instance methods:\nEvery instance of the class have different set of data associated with them in the form of instance variables and other instance related values. The methods used to manipulate/calculate the data/values of an individual instance are called instance methods.\n\nIn our example of Car class, the get_speed(), apply_brakes() are the methods applied on each instance. Here, we need to get it for all the different instances. Therefore, the methods used to calculate these values are instance methods. e.g.\n\n\nTo access the instance methods:\n```python\ncar = Car(\"Harrier\", \"grey\", 180)\ncar.description()\nprint(car.get_speed())\n```\n\n### Class methods\nThe methods that are not related to an individual instance of a class but called upon the class itself. Just like the class variables, class methods are also shared by all the instances of that class.\n\nIn our example of Car class, if we need to work upon the class variables like year (MAKE is constant here. By python convention if the name of the variable is all uppercase it means that variable is not to be changed) we should get it done through a class method. As this will be applicable to all the instances. e. g.\n\n```python\n    @classmethod\n    def change_year(cls, new_year):\n        cls.year = new_year\n        return cls.year\n\ncar1 = Car(\"Harrier\", \"grey\", 180)\ncar2 = Car(\"Nexon\", \"Dark Grey\", 160)\n\nyear = Car.change_year(2023)\nprint(year)\nprint(car1.year)\nprint(car2.year)\n```\n\nWe use @classmethod decorator to tell python that it is a classmethod. By doing so, the python sends the class itself as this method's first parameter.\n\n### Static method\n\n---\n\n## Helpful In-build Methods:\n### dir(): List all the data and methods associated with `instance car1` and `class Car`.\n```python\nprint(dir(car1))\n# Output:\n['MAKE', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'accelerate', 'apply_brake', 'change_year', 'category', 'description', 'get_speed', 'model', 'speed', 'year']\n\nPrint(dir(Car))\n['MAKE', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'accelerate', 'apply_brake', 'change_year', 'description', 'get_speed', 'year']\n```\n\n### MRO: Methods Resolution Order\nIn example_2_animal_class we can check the MRO for the child classes Dog and Cat.\n```python\nprint(Dog.__mro__)\n\n# Output:\n(\u003cclass '__main__.Dog'\u003e, \u003cclass '__main__.Animal'\u003e, \u003cclass 'object'\u003e)\n```\n### is_instance(): \n```python\nprint(isinstance(cat1, Cat))\n\n# Output:\nTrue\n```\n\n### Help():\n```python\n# From the examples/2_2_animal_class.py\nprint(help(cat1))\n```\n### Output:\n```bash\nHelp on Cat in module __main__ object:\n\nclass Cat(Animal)\n |  Cat(name, age, color)\n |  \n |  Method resolution order:\n |      Cat\n |      Animal\n |      builtins.object\n |  \n |  Methods defined here:\n |  \n |  __init__(self, name, age, color)\n |      Initialize self.  See help(type(self)) for accurate signature.\n |  \n |  description(self)\n |  \n |  get_speed(self, speed)\n |  \n |  speak(self, sound)\n |  \n |  ----------------------------------------------------------------------\n |  Methods inherited from Animal:\n |  \n |  __str__(self)\n |      Return str(self).\n |  \n |  jump(self)\n |  \n |  walk(self)\n |  \n |  ----------------------------------------------------------------------\n |  Data descriptors inherited from Animal:\n |  \n |  __dict__\n |      dictionary for instance variables (if defined)\n |  \n |  __weakref__\n |      list of weak references to the object (if defined)  \n(END)\n```\n\n### __dict__ method\n```python\nprint(cat1.__dict__)\n\n# Output:\n{'name': 'Luna', 'age': 2, 'color': 'brown'}\n\nprint(Dog.__dict__)\n\n# Output:\n{'__module__': '__main__', '__init__': \u003cfunction Dog.__init__ at 0x7f295e935280\u003e, 'description': \u003cfunction Dog.description at 0x7f295e935310\u003e, 'speak': \u003cfunction Dog.speak at 0x7f295e9353a0\u003e, 'speed': \u003cfunction Dog.speed at 0x7f295e935430\u003e, '__doc__': None}\n\nprint(Animal.__dict__)\n# Output:\n{'__module__': '__main__', '__init__': \u003cfunction Animal.__init__ at 0x7f295e98ef70\u003e, '__str__': \u003cfunction Animal.__str__ at 0x7f295e935040\u003e, 'walk': \u003cfunction Animal.walk at 0x7f295e9350d0\u003e, 'jump': \u003cfunction Animal.jump at 0x7f295e935160\u003e, 'speak': \u003cfunction Animal.speak at 0x7f295e9351f0\u003e, '__dict__': \u003cattribute '__dict__' of 'Animal' objects\u003e, '__weakref__': \u003cattribute '__weakref__' of 'Animal' objects\u003e, '__doc__': None}\n```\n\n---\n\n## OOPs concepts:\n\n### Inheritance\n**Definition**: Child object with attributes and methods of the parent class. Can be a single or multiple-inheritance.\n\n**Benefits**: Code-reusability\n\n**How to achieve**: Create base or parent classes, and for child or derived classes inherit the parent class. \n\n**Example**: Create Car class, and inherit it for ElectricCars, CNGCars and Petrol or DieselCars.\n\n\n\n### Polymorphism\n**Definition**: Having many forms(Poly = multiple, morph = forms). The process of using a function in different ways for different data input. \n\n**Benefits**: Can create the same template or specific implementation for future objects in the base class and modify the functionality of the individual derived class.(Method-overriding a run-time polymorphism)\n\n**How to achieve**: Can be achieved with or without Inheritance. The derived class method name should be the same as the parent class name.\n\n**Examples**: We have two classes, Dog and Cat inherited from an Animal base class. The **speak method** of both of the derived class can not have the same value. for Dog class it return **bark** but for Cat it should return **Meow**.\n\n### Encapsulation\n**Definition**: Restrict access to properties and methods. Works as a wrapper to conceal data within a class. It is carried out at the implementation level. It is the process of hiding the data involved in the code.\n\n**Benefits**: Restricting the access to the protected and private methods and preventing the accidental modification.\n\n**How to achieve**: Use Pythonic convention of leading single underscore for naming protected variables and methods and leading double underscore to create private variables and methods. We can allow the changes to the attributes through methods only. \n\n**Examples**:  _variable_name, _method_name for protected and __variable_name, __method_name for private variables and methods.\n\n### Abstraction:\n**Definition**: Abstraction is used through encapsulation by hiding the internal functionality or implementation logic  from the users. It is carried out at the design level. It is the process of hiding the details of the implementation of the code.\n\n**Benefits**: Used to hide details and show only the functionalities of the class.\nReduce the complexity of the code.\n\n**How to achieve**: By creating abstract classes and interfaces.\n\n---\n\nTo avoid the temptation of writing classes for every problem at hand, and everywhere we like do watch this vice. [Stop writing classes](https://www.youtube.com/watch?v=o9pEzgHorH0)\n\n---\n\nThis tutorial is still under development. If you find any spelling, grammatical or syntax error, convey it through raising issues. There may be other concept related mistakes, if you found any please raise issue, or discuss.","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frampal-punia%2Fpython-class-tutorial","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frampal-punia%2Fpython-class-tutorial","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frampal-punia%2Fpython-class-tutorial/lists"}