{"id":780,"date":"2023-05-03T18:17:49","date_gmt":"2023-05-03T18:17:49","guid":{"rendered":"https:\/\/www.programminginpython.com\/?p=780"},"modified":"2023-05-03T18:17:49","modified_gmt":"2023-05-03T18:17:49","slug":"python-oop-concepts","status":"publish","type":"post","link":"https:\/\/www.programminginpython.com\/python-oop-concepts\/","title":{"rendered":"Python OOP Concepts: A Comprehensive Guide"},"content":{"rendered":"<p>Hello Python enthusiasts, welcome back to <a href=\"\/\" target=\"_blank\" rel=\"noopener\">Programming In Python<\/a>! Here in this article, I will try to briefly explain and cover the Python OOP concepts<\/p>\n<h2>Python OOP Concepts<\/h2>\n<p>Object-oriented programming (OOP) is a programming paradigm that emphasizes the use of classes and objects to structure code and solve complex problems. Python is an object-oriented programming language that supports many OOP concepts, including:<\/p>\n<p>1. Classes and Objects<br \/>\n2. Encapsulation<br \/>\n3. Abstraction<br \/>\n4. Inheritance<br \/>\n5. Polymorphism<br \/>\n6. Access Modifiers<br \/>\n7. Abstract Classes<br \/>\n8. Interfaces<\/p>\n<p>In this article, we will discuss each of these concepts in more detail.<\/p>\n<h2>Classes and Objects<\/h2>\n<p>Classes are user-defined blueprints that define the attributes and methods of objects. Objects are instances of classes that can be created and manipulated in code.<\/p>\n<p>Here is an example of a class in Python that defines a simple Person object:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">class Person:\r\ndef __init__(self, name, age):\r\nself.name = name\r\nself.age = age\r\n\r\ndef say_hello(self):\r\nprint(f\"Hello, my name is {self.name} and I am {self.age} years old.\")\r\n\r\nperson = Person(\"Alice\", 30)\r\nperson.say_hello()\r\n<\/pre>\n<p>In this example, we define a `Person` class with an `_init_` method that initializes the `name` and `age` attributes of the object. We also define a `say_hello` method that prints a greeting using the object&#8217;s `name` and `age` attributes. We then create a `Person` object called `person` with the name &#8220;Alice&#8221; and age 30, and we call the `say_hello` method on the object.<\/p>\n<blockquote><p>Ad:<br \/>\n<span style=\"font-size: 18pt;\">Learn Python Programming Masterclass \u2013 <a href=\"https:\/\/bit.ly\/python-programming-masterclass\" target=\"_blank\" rel=\"noopener\">Enroll Now<\/a>.<\/span><br \/>\n<span style=\"font-size: 12px;\">Udemy<\/span><\/p><\/blockquote>\n<h2>Encapsulation<\/h2>\n<p>Encapsulation is the concept of wrapping data and methods together in a class so that they are not accessible from outside the class. Encapsulation allows us to hide the implementation details of a class and only expose the necessary functionality.<\/p>\n<p>In Python, we can use naming conventions to indicate the intended access level of a class or method. For example, we can prefix a variable or method name with an underscore to indicate that it should be treated as private.<\/p>\n<p>Here is an example of a class in Python that uses encapsulation:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">class BankAccount:\r\ndef __init__(self, account_number, balance):\r\nself._account_number = account_number\r\nself._balance = balance\r\n\r\ndef deposit(self, amount):\r\nself._balance += amount\r\n\r\ndef withdraw(self, amount):\r\nif amount &gt; self._balance:\r\nraise ValueError(\"Insufficient balance\")\r\nself._balance -= amount\r\n\r\ndef get_balance(self):\r\nreturn self._balance\r\n<\/pre>\n<p>In this example, we define a `BankAccount` class with two private attributes `_account_number` and `_balance`, and three methods `deposit`, `withdraw`, and `get_balance`. The methods are used to manipulate the object&#8217;s balance attribute, but the attributes themselves are private and cannot be accessed directly from outside the class.<\/p>\n<h2>Abstraction<\/h2>\n<p>Abstraction is the concept of focusing on the essential features of an object and ignoring the details that are not relevant to its behavior. Abstraction allows us to create more generic and reusable classes and methods.<\/p>\n<p>In Python, we can use abstract classes and interfaces to implement abstraction.<\/p>\n<h2>Inheritance<\/h2>\n<p>Inheritance is the concept of creating a new class that is a modified version of an existing class. The new class, called the subclass, inherits the attributes and methods of the existing class, called the superclass, and can also define its own attributes and methods.<\/p>\n<p>In Python, we can define a subclass by inheriting from a superclass using the syntax `class Subclass(Superclass):`.<\/p>\n<p>Here is an example of a subclass in Python that inherits attributes and methods from a superclass:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">class Animal:\r\ndef __init__(self, name):\r\nself.name = name\r\n\r\ndef speak(self):\r\nraise NotImplementedError(\"Subclass must implement abstract method\")\r\n\r\nclass Dog(Animal):\r\ndef speak(self):\r\nreturn \"Woof!\"\r\n\r\nclass Cat(Animal):\r\ndef speak(self):\r\nreturn \"Meow.\"\r\n\r\ndog = Dog(\"Fido\")\r\ncat = Cat(\"Whiskers\")\r\n\r\nprint(dog.name + \": \" + dog.speak())\r\nprint(cat.name + \": \" + cat.speak())\r\n<\/pre>\n<p>In this example, we define an abstract `Animal` class with an `_init_` method that initializes the `name` attribute, and an abstract `speak` method that raises a `NotImplementedError` exception. We then define two subclasses `Dog` and `Cat` that inherit from `Animal` and implement their own `speak` methods. Finally, we create two objects, one of each subclass, and call their `speak` methods.<\/p>\n<h2>Polymorphism<\/h2>\n<p>Polymorphism is the concept of using the same method or function to handle different types of objects. Polymorphism allows us to write more generic and reusable code.<\/p>\n<p>In Python, we can achieve polymorphism through inheritance and duck typing. Duck typing is a programming concept that allows us to determine the type of an object based on its behavior rather than its class.<\/p>\n<p>Here is an example of polymorphism in Python using inheritance:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">class Shape:\r\ndef area(self):\r\nraise NotImplementedError(\"Subclass must implement abstract method\")\r\n\r\nclass Rectangle(Shape):\r\ndef __init__(self, width, height):\r\nself.width = width\r\nself.height = height\r\n\r\ndef area(self):\r\nreturn self.width * self.height\r\n\r\nclass Circle(Shape):\r\ndef __init__(self, radius):\r\nself.radius = radius\r\n\r\ndef area(self):\r\nreturn 3.14 * self.radius * self.radius\r\n\r\nshapes = [Rectangle(5, 10), Circle(7)]\r\n\r\nfor shape in shapes:\r\nprint(\"Area:\", shape.area())\r\n<\/pre>\n<p>In this example, we define an abstract `Shape` class with an abstract `area` method, and two subclasses `Rectangle` and `Circle` that inherit from `Shape` and implement their own `area` methods. We then create a list of `Shape` objects, which includes one `Rectangle` and one `Circle`, and call their `area` methods in a loop.<\/p>\n<blockquote><p>Ad:<br \/>\n<span style=\"font-size: 18pt;\">Learn Python Programming Masterclass \u2013 <a href=\"https:\/\/bit.ly\/python-programming-masterclass\" target=\"_blank\" rel=\"noopener\">Enroll Now<\/a>.<\/span><br \/>\n<span style=\"font-size: 12px;\">Udemy<\/span><\/p><\/blockquote>\n<h2>Access Modifiers<\/h2>\n<p>Access modifiers are used to control the visibility and accessibility of attributes and methods in a class. In Python, we can use naming conventions to indicate the intended access level of a class or method. We can prefix a variable or method name with a single underscore `_` to indicate that it should be treated as protected, and with two underscores `__` to indicate that it should be treated as private.<\/p>\n<p>Here is an example of access modifiers in Python:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">class Car:\r\ndef __init__(self, make, model, year):\r\nself.make = make\r\nself.model = model\r\nself.year = year\r\nself._odometer = 0\r\nself.__engine_size = \"2.0L\"\r\n\r\ndef drive(self, miles):\r\nself._odometer += miles\r\n\r\ndef get_odometer(self):\r\nreturn self._odometer\r\n\r\ndef get_engine_size(self):\r\nreturn self.__engine_size\r\n\r\ncar = Car(\"Toyota\", \"Camry\", 2022)\r\ncar.drive(1000)\r\nprint(\"Odometer:\", car.get_odometer())\r\nprint(\"Engine Size:\", car.get_engine_size())\r\n<\/pre>\n<p>In this example, we define a `Car` class with four public attributes `make`, `model`, `year`, and `_odometer`, and one private attribute `__engine_size`. We also define three methods `drive`, `get_odometer`, and `get_engine_size`, where `drive` and `get_odometer` are public methods, and `get_engine_size` is a private method.<\/p>\n<h2>Conclusion<\/h2>\n<p>Object-oriented programming is a powerful paradigm that allows us to write more organized, reusable, and maintainable code. Python provides all the necessary features and tools to support OOP, including classes, objects, inheritance, polymorphism, and access modifiers.<\/p>\n<p>In this article, we have covered the basics of OOP in Python, including classes and objects, inheritance and polymorphism, and access modifiers. We have also provided examples of each concept to help you understand how they work in practice.<\/p>\n<p>We hope that this article has helped you to understand the basics of OOP in Python and inspired you to explore this paradigm further. With more practice and experience, you will be able to design and implement more complex and sophisticated systems using OOP principles.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hello Python enthusiasts, welcome back to Programming In Python! Here in this article, I will try to briefly explain and cover the Python OOP concepts Python OOP Concepts Object-oriented programming (OOP) is a programming paradigm that emphasizes the use of classes and objects to structure code and solve complex problems. Python is an object-oriented programming&#8230;<\/p>\n","protected":false},"author":1,"featured_media":783,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[219],"tags":[223,221,224,225,222,220],"class_list":["post-780","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python-oop","tag-abstraction","tag-classes","tag-encapsulation","tag-interfaces","tag-objects","tag-oop"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.4 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Python OOP Concepts: A Comprehensive Guide<\/title>\n<meta name=\"description\" content=\"Learn the basics of Python OOP concepts, including classes, inheritance, and access modifiers. Get started with examples and explanations.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.programminginpython.com\/python-oop-concepts\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python OOP Concepts: A Comprehensive Guide\" \/>\n<meta property=\"og:description\" content=\"Learn the basics of Python OOP concepts, including classes, inheritance, and access modifiers. Get started with examples and explanations.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.programminginpython.com\/python-oop-concepts\/\" \/>\n<meta property=\"og:site_name\" content=\"Programming In Python\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/programminginpython\" \/>\n<meta property=\"article:published_time\" content=\"2023-05-03T18:17:49+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.programminginpython.com\/wp-content\/uploads\/2023\/05\/Python-OOP.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"600\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"AVINASH NETHALA\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@python_pip\" \/>\n<meta name=\"twitter:site\" content=\"@python_pip\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"AVINASH NETHALA\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python OOP Concepts: A Comprehensive Guide","description":"Learn the basics of Python OOP concepts, including classes, inheritance, and access modifiers. Get started with examples and explanations.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.programminginpython.com\/python-oop-concepts\/","og_locale":"en_US","og_type":"article","og_title":"Python OOP Concepts: A Comprehensive Guide","og_description":"Learn the basics of Python OOP concepts, including classes, inheritance, and access modifiers. Get started with examples and explanations.","og_url":"https:\/\/www.programminginpython.com\/python-oop-concepts\/","og_site_name":"Programming In Python","article_publisher":"https:\/\/www.facebook.com\/programminginpython","article_published_time":"2023-05-03T18:17:49+00:00","og_image":[{"width":1200,"height":600,"url":"https:\/\/www.programminginpython.com\/wp-content\/uploads\/2023\/05\/Python-OOP.webp","type":"image\/webp"}],"author":"AVINASH NETHALA","twitter_card":"summary_large_image","twitter_creator":"@python_pip","twitter_site":"@python_pip","twitter_misc":{"Written by":"AVINASH NETHALA","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.programminginpython.com\/python-oop-concepts\/#article","isPartOf":{"@id":"https:\/\/www.programminginpython.com\/python-oop-concepts\/"},"author":{"name":"AVINASH NETHALA","@id":"https:\/\/www.programminginpython.com\/#\/schema\/person\/9a3c14fe46d422ebf783ee61de1e788c"},"headline":"Python OOP Concepts: A Comprehensive Guide","datePublished":"2023-05-03T18:17:49+00:00","mainEntityOfPage":{"@id":"https:\/\/www.programminginpython.com\/python-oop-concepts\/"},"wordCount":928,"commentCount":0,"publisher":{"@id":"https:\/\/www.programminginpython.com\/#organization"},"image":{"@id":"https:\/\/www.programminginpython.com\/python-oop-concepts\/#primaryimage"},"thumbnailUrl":"https:\/\/www.programminginpython.com\/wp-content\/uploads\/2023\/05\/Python-OOP.webp","keywords":["abstraction","classes","Encapsulation","Interfaces","objects","OOP"],"articleSection":["Python OOP"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.programminginpython.com\/python-oop-concepts\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.programminginpython.com\/python-oop-concepts\/","url":"https:\/\/www.programminginpython.com\/python-oop-concepts\/","name":"Python OOP Concepts: A Comprehensive Guide","isPartOf":{"@id":"https:\/\/www.programminginpython.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.programminginpython.com\/python-oop-concepts\/#primaryimage"},"image":{"@id":"https:\/\/www.programminginpython.com\/python-oop-concepts\/#primaryimage"},"thumbnailUrl":"https:\/\/www.programminginpython.com\/wp-content\/uploads\/2023\/05\/Python-OOP.webp","datePublished":"2023-05-03T18:17:49+00:00","description":"Learn the basics of Python OOP concepts, including classes, inheritance, and access modifiers. Get started with examples and explanations.","breadcrumb":{"@id":"https:\/\/www.programminginpython.com\/python-oop-concepts\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.programminginpython.com\/python-oop-concepts\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.programminginpython.com\/python-oop-concepts\/#primaryimage","url":"https:\/\/www.programminginpython.com\/wp-content\/uploads\/2023\/05\/Python-OOP.webp","contentUrl":"https:\/\/www.programminginpython.com\/wp-content\/uploads\/2023\/05\/Python-OOP.webp","width":1200,"height":600,"caption":"Python OOP Concepts: A Comprehensive Guide"},{"@type":"BreadcrumbList","@id":"https:\/\/www.programminginpython.com\/python-oop-concepts\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.programminginpython.com\/"},{"@type":"ListItem","position":2,"name":"Python OOP Concepts: A Comprehensive Guide"}]},{"@type":"WebSite","@id":"https:\/\/www.programminginpython.com\/#website","url":"https:\/\/www.programminginpython.com\/","name":"Programming In Python","description":"All About Python","publisher":{"@id":"https:\/\/www.programminginpython.com\/#organization"},"alternateName":"pip","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.programminginpython.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.programminginpython.com\/#organization","name":"Programming In Python","alternateName":"PIP","url":"https:\/\/www.programminginpython.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.programminginpython.com\/#\/schema\/logo\/image\/","url":"https:\/\/www.programminginpython.com\/wp-content\/uploads\/2023\/04\/pip_logo_500_500.png","contentUrl":"https:\/\/www.programminginpython.com\/wp-content\/uploads\/2023\/04\/pip_logo_500_500.png","width":500,"height":500,"caption":"Programming In Python"},"image":{"@id":"https:\/\/www.programminginpython.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/programminginpython","https:\/\/x.com\/python_pip","https:\/\/www.youtube.com\/programminginpython","https:\/\/github.com\/avinashn\/programminginpython.com"]},{"@type":"Person","@id":"https:\/\/www.programminginpython.com\/#\/schema\/person\/9a3c14fe46d422ebf783ee61de1e788c","name":"AVINASH NETHALA","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.programminginpython.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/ed52e7670d7db94820c7430d324103ccdecb16d86611d5b29064aa9ce25a958b?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/ed52e7670d7db94820c7430d324103ccdecb16d86611d5b29064aa9ce25a958b?s=96&d=mm&r=g","caption":"AVINASH NETHALA"},"sameAs":["https:\/\/www.programminginpython.com\/"],"url":"https:\/\/www.programminginpython.com\/author\/avinash\/"}]}},"jetpack_featured_media_url":"https:\/\/www.programminginpython.com\/wp-content\/uploads\/2023\/05\/Python-OOP.webp","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.programminginpython.com\/wp-json\/wp\/v2\/posts\/780","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.programminginpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.programminginpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.programminginpython.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.programminginpython.com\/wp-json\/wp\/v2\/comments?post=780"}],"version-history":[{"count":3,"href":"https:\/\/www.programminginpython.com\/wp-json\/wp\/v2\/posts\/780\/revisions"}],"predecessor-version":[{"id":784,"href":"https:\/\/www.programminginpython.com\/wp-json\/wp\/v2\/posts\/780\/revisions\/784"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.programminginpython.com\/wp-json\/wp\/v2\/media\/783"}],"wp:attachment":[{"href":"https:\/\/www.programminginpython.com\/wp-json\/wp\/v2\/media?parent=780"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.programminginpython.com\/wp-json\/wp\/v2\/categories?post=780"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.programminginpython.com\/wp-json\/wp\/v2\/tags?post=780"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}