{"id":133,"date":"2024-01-25T13:26:35","date_gmt":"2024-01-25T13:26:35","guid":{"rendered":"https:\/\/learnpython.elegantwallp.com\/?p=133"},"modified":"2024-01-25T13:26:36","modified_gmt":"2024-01-25T13:26:36","slug":"python-object-oriented-programming","status":"publish","type":"post","link":"https:\/\/learnpython.elegantwallp.com\/2024\/01\/25\/python-object-oriented-programming\/","title":{"rendered":"Python Object-oriented Programming"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you\u2019ll learn object-oriented programming in Python, including essential concepts such as objects, classes, attributes, methods, inheritances, overriding methods, etc.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to Python Object-oriented Programming<\/h2>\n\n\n\n<p>Everything in Python is an object. An object has a state and behaviors. To create an object, you define a class first. And then, from the class, you can create one or more objects. The objects are instances of a class.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Define a class<\/h2>\n\n\n\n<p>To define a\u00a0class, you use the\u00a0<code>class<\/code>\u00a0keyword followed by the class name. For example, the following defines a\u00a0<code>Person<\/code>\u00a0class:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>class Person: pass<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>To create an object from the\u00a0<code>Person<\/code>\u00a0class, you use the class name followed by parentheses\u00a0<code>()<\/code>, like calling a function:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>person = Person()<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>In this example, the\u00a0<code>person<\/code>\u00a0is an instance of the\u00a0<code>Person<\/code>\u00a0class. Classes are\u00a0callable.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Define instance attributes<\/h2>\n\n\n\n<p>Python is dynamic. It means that you can add an attribute to an instance of a class dynamically at runtime.<\/p>\n\n\n\n<p>For example, the following adds the\u00a0<code>name<\/code>\u00a0attribute to the\u00a0<code>person<\/code>\u00a0object:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>person.name = 'John'<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>However, if you create another&nbsp;<code>Person<\/code>&nbsp;object, the new object won\u2019t have the&nbsp;<code>name<\/code>&nbsp;attribute.<\/p>\n\n\n\n<p>To define and initialize an attribute for all instances of a class, you use the\u00a0<code>__init__<\/code>\u00a0method. The following defines the\u00a0<code>Person<\/code>\u00a0class with two instance attributes\u00a0<code>name<\/code>\u00a0and\u00a0<code>age<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>class Person: def __init__(self, name, age): self.name = name self.age = age<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>When you create a&nbsp;<code>Person<\/code>&nbsp;object, Python automatically calls the&nbsp;<code>__init__<\/code>&nbsp;method to initialize the instance attributes. In the&nbsp;<code>__init__<\/code>&nbsp;method, the&nbsp;<code>self<\/code>&nbsp;is the instance of the&nbsp;<code>Person<\/code>&nbsp;class.<\/p>\n\n\n\n<p>The following creates a\u00a0<code>Person<\/code>\u00a0object named\u00a0<code>person<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>person = Person('John', 25)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>The\u00a0<code>person<\/code>\u00a0object now has the\u00a0<code>name<\/code>\u00a0and\u00a0<code>age<\/code>\u00a0attributes. To access an instance attribute, you use the dot notation. For example, the following returns the value of the name attribute of the\u00a0<code>person<\/code>\u00a0object:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>person.name<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Define instance methods<\/h2>\n\n\n\n<p>The following adds an instance method called\u00a0<code>greet()<\/code>\u00a0to the\u00a0<code>Person<\/code>\u00a0class:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>class Person: def __init__(self, name, age): self.name = name self.age = age def greet(self): return f\"Hi, it's {self.name}.\"<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>To call an instance method, you also use the dot notation. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>person = Person('John', 25) print(person.greet())<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>Hi, it's John<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Define class attributes<\/h2>\n\n\n\n<p>Unlike instance attributes, class attributes are shared by all instances of the class. They are helpful if you want to define class constants or variables that keep track of the number of instances of a class.<\/p>\n\n\n\n<p>For example, the following defines the\u00a0<code>counter<\/code>\u00a0class attribute in the\u00a0<code>Person<\/code>\u00a0class:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>class Person: counter = 0 def __init__(self, name, age): self.name = name self.age = age def greet(self): return f\"Hi, it's {self.name}.\"<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>You can access the&nbsp;<code>counter<\/code>&nbsp;attribute from the&nbsp;<code>Person<\/code>&nbsp;class:<code>Person.counter<\/code><small>Code language: Python (python)<\/small><\/p>\n\n\n\n<p>Or from any instances of the\u00a0<code>Person<\/code>\u00a0class:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>person = Person('John',25) person.counter<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>To make the\u00a0<code>counter<\/code>\u00a0variable more useful, you can increase its value by one once an object is created. To do it, you increase the\u00a0<code>counter<\/code>\u00a0class attribute in the\u00a0<code>__init__<\/code>\u00a0method:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>class Person: counter = 0 def __init__(self, name, age): self.name = name self.age = age Person.counter += 1 def greet(self): return f\"Hi, it's {self.name}.\"<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>The following creates two instances of the\u00a0<code>Person<\/code>\u00a0class and shows the value of the\u00a0<code>counter<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>p1 = Person('John', 25) p2 = Person('Jane', 22) print(Person.counter)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>2<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Define class method<\/h2>\n\n\n\n<p>Like a class attribute, a class method is shared by all instances of the class. The first argument of a class method is the class itself. By convention, its name is&nbsp;<code>cls<\/code>. Python automatically passes this argument to the class method. Also, you use the @classmethod decorator to decorate a class method.<\/p>\n\n\n\n<p>The following example defines a class method that returns an anonymous\u00a0<code>Person<\/code>\u00a0object:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>class Person: counter = 0 def __init__(self, name, age): self.name = name self.age = age Person.counter += 1 def greet(self): return f\"Hi, it's {self.name}.\" @classmethod def create_anonymous(cls): return Person('Anonymous', 22)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>The following shows how to call the\u00a0<code>create_anonymous()<\/code>\u00a0class method:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>anonymous = Person.create_anonymous() print(anonymous.name) <em># Anonymous<\/em><\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Define static method<\/h2>\n\n\n\n<p>A static method is not bound to a class or any instances of the class. In Python, you use static methods to group logically related functions in a class. To define a static method, you use the&nbsp;<code>@staticmethod<\/code>&nbsp;decorator.<\/p>\n\n\n\n<p>For example, the following defines a class\u00a0<code>TemperatureConverter<\/code>\u00a0that has two static methods that convert from celsius to Fahrenheit and vice versa:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>class TemperatureConverter: @staticmethod def celsius_to_fahrenheit(c): return 9 * c \/ 5 + 32 @staticmethod def fahrenheit_to_celsius(f): return 5 * (f - 32) \/ 9<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>To call a static method, you use the\u00a0<code>ClassName.static_method_name()<\/code>\u00a0syntax. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>f = TemperatureConverter.celsius_to_fahrenheit(30) print(f) <em># 86<\/em><\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Notice that Python doesn\u2019t implicitly pass an instance (<code>self<\/code>) as well as class (<code>cls<\/code>) as the first argument of a static method.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Single inheritance<\/h2>\n\n\n\n<p>A class can reuse another class by inheriting it. When a child class inherits from a parent class, the child class can access the attributes and methods of the parent class.<\/p>\n\n\n\n<p>For example, you can define an\u00a0<code>Employee<\/code>\u00a0class that inherits from the\u00a0<code>Person<\/code>\u00a0class:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>class Employee(Person): def __init__(self, name, age, job_title): super().__init__(name, age) self.job_title = job_title<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Inside the&nbsp;<code>__init__<\/code>&nbsp;method of the&nbsp;<code>Employee<\/code>&nbsp;class calls the&nbsp;<code>__init__<\/code>method of the&nbsp;<code>Person<\/code>&nbsp;class to initialize the&nbsp;<code>name<\/code>&nbsp;and&nbsp;<code>age<\/code>&nbsp;attributes. The&nbsp;<code>super()<\/code>&nbsp;allows a child class to access a method of the parent class.<\/p>\n\n\n\n<p>The&nbsp;<code>Employee<\/code>&nbsp;class extends the&nbsp;<code>Person<\/code>&nbsp;class by adding one more attribute called&nbsp;<code>job_title<\/code>.<\/p>\n\n\n\n<p>The\u00a0<code>Person<\/code>\u00a0is the parent class while the\u00a0<code>Employee<\/code>\u00a0is a child class. To override the\u00a0<code>greet()<\/code>\u00a0method in the\u00a0<code>Person<\/code>\u00a0class, you can define the\u00a0<code>greet()<\/code>\u00a0method in the\u00a0<code>Employee<\/code>\u00a0class as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>class Employee(Person): def __init__(self, name, age, job_title): super().__init__(name, age) self.job_title = job_title def greet(self): return super().greet() + f\" I'm a {self.job_title}.\"<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>The&nbsp;<code>greet()<\/code>&nbsp;method in the&nbsp;<code>Employee<\/code>&nbsp;is also called the&nbsp;<code>greet()<\/code>&nbsp;method of the&nbsp;<code>Person<\/code>&nbsp;class. In other words, it delegates to a method of the parent class.<\/p>\n\n\n\n<p>The following creates a new instance of the\u00a0<code>Employee<\/code>\u00a0class and call the\u00a0<code>greet()<\/code>\u00a0method:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>employee = Employee('John', 25, 'Python Developer') print(employee.greet())<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>Hi, it's John. I'm a Python Developer.<\/code><\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Summary: in this tutorial, you\u2019ll learn object-oriented programming in Python, including essential concepts such as objects, classes, attributes, methods, inheritances, overriding methods, etc. Introduction to Python Object-oriented Programming Everything in Python is an object. An object has a state and behaviors. To create an object, you define a class first. And then, from the class, [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[25],"tags":[],"class_list":["post-133","post","type-post","status-publish","format-standard","hentry","category-1-classes-and-objects"],"_links":{"self":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/133","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/comments?post=133"}],"version-history":[{"count":1,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/133\/revisions"}],"predecessor-version":[{"id":134,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/133\/revisions\/134"}],"wp:attachment":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/media?parent=133"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/categories?post=133"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/tags?post=133"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}