{"id":8176,"date":"2023-08-20T16:00:22","date_gmt":"2023-08-20T10:30:22","guid":{"rendered":"https:\/\/tutorpython.com\/?p=8176"},"modified":"2023-10-19T15:15:36","modified_gmt":"2023-10-19T09:45:36","slug":"class-objects-in-python","status":"publish","type":"post","link":"https:\/\/tutorpython.com\/class-objects-in-python","title":{"rendered":"Class, Objects in Python"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_80 counter-hierarchy ez-toc-counter ez-toc-transparent ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">In This Article<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/tutorpython.com\/class-objects-in-python\/#Classes_in_Python\" >Classes in Python<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/tutorpython.com\/class-objects-in-python\/#Objects_in_Python\" >Objects in Python<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/tutorpython.com\/class-objects-in-python\/#Access_Class_Attributes_Using_Objects_in_Python\" >Access Class Attributes Using Objects in Python<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/tutorpython.com\/class-objects-in-python\/#Create_Multiple_Objects_of_Python_Class\" >Create Multiple Objects of Python Class<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/tutorpython.com\/class-objects-in-python\/#Python_Methods\" >Python Methods<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/tutorpython.com\/class-objects-in-python\/#Constructors_in_Python\" >Constructors in Python<\/a><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"Classes_in_Python\"><\/span>Classes in Python<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>In Python, classes are a fundamental feature of <a href=\"https:\/\/tutorpython.com\/tutorial\/object-oriented-programming-in-python\" target=\"_blank\" rel=\"noopener\">object-oriented programming<\/a> (OOP). They allow you to define a blueprint or template for creating objects, which can have attributes (<a href=\"https:\/\/tutorpython.com\/tutorial\/variables-in-python\" target=\"_blank\" rel=\"noopener\">variables<\/a>) and methods (<a href=\"https:\/\/tutorpython.com\/tutorial\/functions-in-python\" target=\"_blank\" rel=\"noopener\">functions<\/a>). To create a class in Python, we use the <code>class<\/code> <a href=\"https:\/\/tutorpython.com\/tutorial\/keywords-identifiers-in-python\" target=\"_blank\" rel=\"noopener\">keyword<\/a> followed by the name of the class. For example:<\/p>\n<pre><code class=\"language-python\">class MyClass:\r\n    pass\r\n<\/code><\/pre>\n<p>This defines a class called <code>MyClass<\/code> with no attributes or methods. We can then create instances of this class by calling the class name as if it were a function:<\/p>\n<pre><code class=\"language-python\">obj = MyClass()\r\n<\/code><\/pre>\n<p>We can also define attributes and methods for the class using the <code>def<\/code> keyword:<\/p>\n<pre><code class=\"language-python\">class MyClass:\r\n    def __init__(self, name):\r\n        self.name = name\r\n\r\n    def greet(self):\r\n        print(f\"Hello, {self.name}!\")\r\n\r\nobj = MyClass(\"Alice\")\r\nobj.greet()  # Output: Hello, Alice!\r\n<\/code><\/pre>\n<p>Here, we define a constructor method (<code>__init__<\/code>) that takes a <code>name<\/code> parameter and initializes an instance variable <code>self.name<\/code> with it. We also define a <code>greet<\/code> method that prints a greeting using the <code>self.name<\/code> variable.<\/p>\n<p>One important concept in OOP is inheritance, where we can create a new class that inherits attributes and methods from an existing class.<\/p>\n<p>For example:<\/p>\n<pre><code class=\"language-python\">class MySubclass(MyClass):\r\n    def __init__(self, name, age):\r\n        super().__init__(name)\r\n        self.age = age\r\n\r\n    def greet(self):\r\n        print(f\"Hello, {self.name}! You are {self.age} years old.\")\r\n\r\nobj = MySubclass(\"Bob\", 30)\r\nobj.greet()  # Output: Hello, Bob! You are 30 years old.\r\n<\/code><\/pre>\n<p>Here, we define a subclass <code>MySubclass<\/code> that inherits from <code>MyClass<\/code>.<\/p>\n<p>We define a new constructor that takes an additional <code>age<\/code> parameter and initializes an instance variable <code>self.age<\/code> with it. We also override the <code>greet<\/code> method to include the <code>self.age<\/code> variable.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Objects_in_Python\"><\/span>Objects in Python<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>In Python, an object is an instance of a class. When we create a new object, we are creating a new instance of that class with its own unique set of attributes and methods. Objects are the basic building blocks of object-oriented programming in Python.<\/p>\n<p>To create an object in Python, we first need to define a class. We can do this using the <code>class<\/code> keyword, followed by the name of the class and any attributes and methods we want to include:<\/p>\n<pre><code class=\"language-python\">class MyClass:\r\n    def __init__(self, name):\r\n        self.name = name\r\n\r\n    def greet(self):\r\n        print(f\"Hello, {self.name}!\")\r\n<\/code><\/pre>\n<p>Here, we define a class called <code>MyClass<\/code> with a constructor method (<code>__init__<\/code>) that takes a <code>name<\/code> parameter and initializes an instance variable <code>self.name<\/code> with it. We also define a <code>greet<\/code> method that prints a greeting using the <code>self.name<\/code> variable.<\/p>\n<p>To create an object of this class, we simply call the class name as if it were a <a href=\"https:\/\/tutorpython.com\/tutorial\/function-arguments-in-python\" target=\"_blank\" rel=\"noopener\">function, passing in any parameters<\/a> required by the constructor:<\/p>\n<pre><code class=\"language-python\">obj = MyClass(\"Alice\")\r\n<\/code><\/pre>\n<p>This creates a new object for the <code>MyClass<\/code> class with a <code>name<\/code> attribute set to <code>\"Alice\"<\/code>.<\/p>\n<p>We can then access this attribute using dot notation:<\/p>\n<pre><code class=\"language-python\">print(obj.name)  # Output: Alice\r\n<\/code><\/pre>\n<p>We can also call methods on the object using dot notation:<\/p>\n<pre><code class=\"language-python\">obj.greet()  # Output: Hello, Alice!\r\n<\/code><\/pre>\n<p>Objects in Python are dynamically typed, which means that their type can change at runtime.<\/p>\n<p>For example, we can create a new object and assign it to a variable:<\/p>\n<pre><code class=\"language-python\">obj = MyClass(\"Alice\")\r\n<\/code><\/pre>\n<p>We can then assign a new object of a different class to the same variable:<\/p>\n<pre><code class=\"language-python\">obj = SomeOtherClass()\r\n<\/code><\/pre>\n<p>This re-assigns the <code>obj<\/code> variable to a new object of a different class, effectively changing its type. This flexibility is one of the strengths of Python&#8217;s object-oriented programming model.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Access_Class_Attributes_Using_Objects_in_Python\"><\/span>Access Class Attributes Using Objects in Python<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>In Python, we can access class attributes using objects. Class attributes are variables that are defined at the class level and are shared by all instances of the class. To access a class attribute using an object, we use dot notation, just like we would with an instance attribute.<\/p>\n<p>For example, let&#8217;s say we have a class called <code>Person<\/code> with a class attribute called <code>species<\/code>:<\/p>\n<pre><code class=\"language-python\">class Person:\r\n    species = 'human'\r\n\r\n    def __init__(self, name):\r\n        self.name = name\r\n<\/code><\/pre>\n<p>Here, we define a class called <code>Person<\/code> with a class attribute <code>species<\/code> set to <code>'human'<\/code>. We also define a constructor method that takes a <code>name<\/code> parameter and initializes an instance variable <code>self.name<\/code> with it.<\/p>\n<p>To access the <code>species<\/code> attribute using an object, we simply use dot notation:<\/p>\n<pre><code class=\"language-python\">p = Person('Alice')\r\nprint(p.species)  # Output: human\r\n<\/code><\/pre>\n<p>In this example, we create a new object of the <code>Person<\/code> class with a <code>name<\/code> attribute set to <code>\"Alice\"<\/code>. We then access the <code>species<\/code> attribute using dot notation, which returns the value <code>\"human\"<\/code>.<\/p>\n<p>We can also modify class attributes using objects. When we modify a class attribute using an object, it only affects that object &#8211; other objects of the same class will still have the original value of the attribute.<\/p>\n<p>For example:<\/p>\n<pre><code class=\"language-python\">p = Person('Alice')\r\nprint(p.species)  # Output: human\r\n\r\np.species = 'alien'\r\nprint(p.species)  # Output: alien\r\n\r\nq = Person('Bob')\r\nprint(q.species)  # Output: human\r\n<\/code><\/pre>\n<p>Here, we create a new object <code>p<\/code> of the <code>Person<\/code> class and modify its <code>species<\/code> attribute to <code>\"alien\"<\/code>. When we <a href=\"https:\/\/tutorpython.com\/tutorial\/basic-input-output-operations-in-python\" target=\"_blank\" rel=\"noopener\">print<\/a> the <code>species<\/code> attribute using <code>p<\/code>, we get <code>\"alien\"<\/code>. However, when we create a new object <code>q<\/code> of the same class and print its <code>species<\/code> attribute, we get the original value of <code>\"human\"<\/code>.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Create_Multiple_Objects_of_Python_Class\"><\/span>Create Multiple Objects of Python Class<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>In Python, we can create multiple objects of a class. Each object is an instance of the class and has its own set of attributes and methods. To create multiple objects of a class, we simply call the class constructor multiple times with different arguments.<\/p>\n<p>For example, let&#8217;s say we have a class called <code>Person<\/code>:<\/p>\n<pre><code class=\"language-python\">class Person:\r\n    def __init__(self, name, age):\r\n        self.name = name\r\n        self.age = age\r\n\r\n    def greet(self):\r\n        print(f\"Hello, my name is {self.name} and I am {self.age} years old.\")\r\n<\/code><\/pre>\n<p>In this example, we define a class called <code>Person<\/code> with a constructor method that takes <code>name<\/code> and <code>age<\/code> parameters and initializes instance variables <code>self.name<\/code> and <code>self.age<\/code> with them. We also define a <code>greet<\/code> method that prints a greeting using the <code>self.name<\/code> and <code>self.age<\/code> variables.<\/p>\n<p>To create multiple objects of this class, we simply call the constructor multiple times with different arguments:<\/p>\n<pre><code class=\"language-python\">p1 = Person(\"Alice\", 25)\r\np2 = Person(\"Bob\", 30)\r\np3 = Person(\"Charlie\", 35)\r\n<\/code><\/pre>\n<p>Here, we create three objects <code>p1<\/code>, <code>p2<\/code>, and <code>p3<\/code> of the <code>Person<\/code> class with different <code>name<\/code> and <code>age<\/code> attributes. Each object has its own set of attributes and methods and can be manipulated independently.<\/p>\n<p>We can then call methods on each object using dot notation:<\/p>\n<pre><code class=\"language-python\">p1.greet()  # Output: Hello, my name is Alice and I am 25 years old.\r\np2.greet()  # Output: Hello, my name is Bob and I am 30 years old.\r\np3.greet()  # Output: Hello, my name is Charlie and I am 35 years old.\r\n<\/code><\/pre>\n<p>Here, we call the <code>greet<\/code> method on each object, which prints a greeting using the <code>name<\/code> and <code>age<\/code> attributes specific to each object.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Python_Methods\"><\/span>Python Methods<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>In Python, methods are functions that are defined inside a class and are associated with an object of that class. Methods can access and manipulate the attributes of the object, and can also access other methods of the same object or other objects of the same class.<\/p>\n<p>Methods in Python are defined using the <code>def<\/code> keyword, just like regular functions, but they are defined inside a class.<\/p>\n<p>For example, let&#8217;s say we have a class called <code>Person<\/code> with a method called <code>greet<\/code>:<\/p>\n<pre><code class=\"language-python\">class Person:\r\n    def __init__(self, name):\r\n        self.name = name\r\n\r\n    def greet(self):\r\n        print(f\"Hello, my name is {self.name}.\")\r\n<\/code><\/pre>\n<p>Here, we define a class called <code>Person<\/code> with a constructor method that takes a <code>name<\/code> parameter and initializes an instance variable <code>self.name<\/code> with it. We also define a method called <code>greet<\/code> that prints a greeting using the <code>self.name<\/code> variable.<\/p>\n<p>To call the <code>greet<\/code> method on an object of this class, we simply use dot notation:<\/p>\n<pre><code class=\"language-python\">p = Person(\"Alice\")\r\np.greet()  # Output: Hello, my name is Alice.\r\n<\/code><\/pre>\n<p>Here, we create an object <code>p<\/code> of the <code>Person<\/code> class with a <code>name<\/code> attribute set to <code>\"Alice\"<\/code>. We then call the <code>greet<\/code> method on <code>p<\/code>, which prints a greeting using the <code>name<\/code> attribute of <code>p<\/code>.<\/p>\n<p>Methods in Python can also take parameters, just like regular functions.<\/p>\n<p>For example, let&#8217;s say we have a method called <code>change_name<\/code> that takes a new name and updates the <code>name<\/code> attribute of the object:<\/p>\n<pre><code class=\"language-python\">class Person:\r\n    def __init__(self, name):\r\n        self.name = name\r\n\r\n    def greet(self):\r\n        print(f\"Hello, my name is {self.name}.\")\r\n\r\n    def change_name(self, new_name):\r\n        self.name = new_name\r\n<\/code><\/pre>\n<p>Here, we define a method called <code>change_name<\/code> that takes a <code>new_name<\/code> parameter and updates the <code>name<\/code> attribute of the object using the <code>self<\/code> keyword.<\/p>\n<p>To call the <code>change_name<\/code> method on an object, we simply <a href=\"https:\/\/tutorpython.com\/tutorial\/function-arguments-in-python\" target=\"_blank\" rel=\"noopener\">pass the <code>new_name<\/code> parameter<\/a>:<\/p>\n<pre><code class=\"language-python\">p = Person(\"Alice\")\r\np.greet()  # Output: Hello, my name is Alice.\r\n\r\np.change_name(\"Bob\")\r\np.greet()  # Output: Hello, my name is Bob.\r\n<\/code><\/pre>\n<p>Here, we create an object <code>p<\/code> of the <code>Person<\/code> class with a <code>name<\/code> attribute set to <code>\"Alice\"<\/code>.<\/p>\n<p>We then call the <code>greet<\/code> method on <code>p<\/code>, which prints a greeting using the <code>name<\/code> attribute of <code>p<\/code>. We then call the <code>change_name<\/code> method on <code>p<\/code> with a <code>new_name<\/code> parameter of <code>\"Bob\"<\/code>, which updates the <code>name<\/code> attribute of <code>p<\/code>. We then call the <code>greet<\/code> method on <code>p<\/code> again, which prints a greeting using the updated <code>name<\/code> attribute of <code>\"Bob\"<\/code>.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Constructors_in_Python\"><\/span>Constructors in Python<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>In Python, a constructor is a special method that is automatically called when an object of a class is created. The purpose of a constructor is to initialize the instance variables of the object with values passed as arguments, or with default values.<\/p>\n<p>In Python, the constructor method is called <code>__init__()<\/code> and is defined within the class definition. Here&#8217;s an example of a class with a constructor:<\/p>\n<pre><code class=\"language-python\">class Person:\r\n    def __init__(self, name, age):\r\n        self.name = name\r\n        self.age = age\r\n<\/code><\/pre>\n<p>Here, we define a class called <code>Person<\/code> with a constructor method that takes two parameters: <code>name<\/code> and <code>age<\/code>. Inside the constructor, we initialize two instance variables using the values of the parameters.<\/p>\n<p>To create an object of this class, we simply call the class name with the required parameters:<\/p>\n<pre><code class=\"language-python\">p = Person(\"Alice\", 25)\r\n<\/code><\/pre>\n<p>Here, we create an object <code>p<\/code> of the <code>Person<\/code> class with a <code>name<\/code> attribute set to <code>\"Alice\"<\/code> and an <code>age<\/code> attribute set to <code>25<\/code>. The constructor method <code>__init__()<\/code> is automatically called with the arguments <code>\"Alice\"<\/code> and <code>25<\/code>, and initializes the instance variables <code>self.name<\/code> and <code>self.age<\/code> with those values.<\/p>\n<p>If we want to initialize instance variables with default values, we can define a constructor that takes no parameters and initializes the variables with the default values. Here&#8217;s an example:<\/p>\n<pre><code class=\"language-python\">class Person:\r\n    def __init__(self):\r\n        self.name = \"Unknown\"\r\n        self.age = 0\r\n<\/code><\/pre>\n<p>In this example, we define a class called <code>Person<\/code> with a constructor method that takes no parameters. Inside the constructor, we initialize two instance variables <code>self.name<\/code> and <code>self.age<\/code> with default values.<\/p>\n<p>To create an object of this class, we simply call the class name without any parameters:<\/p>\n<pre><code class=\"language-python\">p = Person()\r\n<\/code><\/pre>\n<p>Here, we create an object <code>p<\/code> of the <code>Person<\/code> class with a <code>name<\/code> attribute set to <code>\"Unknown\"<\/code> and an <code>age<\/code> attribute set to <code>0<\/code>. The constructor method <code>__init__()<\/code> is automatically called with no arguments, and initializes the instance variables <code>self.name<\/code> and <code>self.age<\/code> with the default values.<\/p>\n<p>Overall, constructors in Python are a powerful tool for initializing the instance variables of an object with values passed as <a href=\"https:\/\/tutorpython.com\/tutorial\/function-arguments-in-python\" target=\"_blank\" rel=\"noopener\">arguments<\/a> or with default values. By defining constructors within a class and calling them when objects are created, we can create more flexible and dynamic programs.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Classes in Python In Python, classes are a fundamental feature of object-oriented&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[28],"tags":[],"class_list":["post-8176","post","type-post","status-publish","format-standard","hentry","category-tutorial"],"acf":[],"_links":{"self":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts\/8176","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/comments?post=8176"}],"version-history":[{"count":7,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts\/8176\/revisions"}],"predecessor-version":[{"id":8838,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts\/8176\/revisions\/8838"}],"wp:attachment":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/media?parent=8176"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/categories?post=8176"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/tags?post=8176"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}