|
| 1 | +# Classes and objects |
| 2 | + |
| 3 | +## Introduction |
| 4 | + |
| 5 | +Python is an object-oriented programming language. **Object-oriented programming** (OOP) focuses on creating reusable patterns of code, in contrast to procedural programming, which focuses on explicit sequenced instructions. When working on complex programs in particular, object-oriented programming lets you reuse code and write code that is more readable, which in turn makes it more maintainable. |
| 6 | + |
| 7 | +One of the most important concepts in object-oriented programming is the distinction between classes and objects, which are defined as follows: |
| 8 | + |
| 9 | +* **Class** — A blueprint created by a programmer for an object. This defines a set of attributes that will characterize any object that is instantiated from this class. |
| 10 | +* **Object** — An instance of a class. This is the realized version of the class, where the class is manifested in the program. |
| 11 | + |
| 12 | +These are used to create patterns (in the case of classes) and then make use of the patterns (in the case of objects). |
| 13 | + |
| 14 | +In this lecture, we’ll go through creating classes, instantiating objects, initializing attributes with the constructor method, and working with more than one object of the same class. |
| 15 | + |
| 16 | + |
| 17 | +## Classes |
| 18 | + |
| 19 | +Classes are like a blueprint or a prototype that you can define to use to create objects. |
| 20 | + |
| 21 | +We define classes by using the **`class`** keyword, similar to how we define functions by using the **`def`** keyword. |
| 22 | + |
| 23 | +Let’s define a class called `Shark` that has two functions associated with it, one for swimming and one for being awesome: |
| 24 | + |
| 25 | +```python |
| 26 | +# shark.py |
| 27 | + |
| 28 | +class Shark: |
| 29 | + def swim(self): |
| 30 | + print("The shark is swimming.") |
| 31 | + |
| 32 | + def be_awesome(self): |
| 33 | + print("The shark is being awesome.") |
| 34 | +``` |
| 35 | + |
| 36 | +Because these functions are indented under the class `Shark`, they are called *methods*. **Methods** are a special kind of function that are defined within a class. |
| 37 | + |
| 38 | +The argument to these functions is the word `self`, which is a reference to objects that are made based on this class. To reference instances (or objects) of the class, self will always be the first parameter, but it need not be the only one. |
| 39 | + |
| 40 | +Defining this class did not create any `Shark` objects, only the pattern for a `Shark` object that we can define later. That is, if you run the program above at this stage nothing will be returned. |
| 41 | + |
| 42 | +Creating the `Shark` class above provided us with a blueprint for an object. |
| 43 | + |
| 44 | + |
| 45 | +## Objects |
| 46 | + |
| 47 | +An object is an instance of a class. We can take the `Shark` class defined above, and use it to create an object or instance of it. |
| 48 | + |
| 49 | +We’ll make a `Shark` object called `sammy`: |
| 50 | + |
| 51 | +```python |
| 52 | +sammy = Shark() |
| 53 | +``` |
| 54 | + |
| 55 | +Here, we initialized the object `sammy` as an *instance* of the class by setting it equal to `Shark()`. |
| 56 | + |
| 57 | +Now, let’s use the two methods with the `Shark`object `sammy`: |
| 58 | + |
| 59 | +```python |
| 60 | +sammy = Shark() |
| 61 | +sammy.swim() |
| 62 | +sammy.be_awesome() |
| 63 | +``` |
| 64 | + |
| 65 | +The `Shark` object `sammy` is using the two methods `swim()` and `be_awesome()`. We called these using the dot operator (`.`), which is used to reference an attribute of the object. In this case, the attribute is a method and it’s called with parentheses, like how you would also call with a function. |
| 66 | + |
| 67 | +Because the keyword `self` was a parameter of the methods as defined in the `Shark` class, the `sammy` object gets passed to the methods. The `self` parameter ensures that the methods have a way of referring to object attributes. |
| 68 | + |
| 69 | +When we call the methods, however, nothing is passed inside the parentheses, the object `sammy` is being automatically passed with the dot operator. |
| 70 | + |
| 71 | +Let’s add the object within the context of a program: |
| 72 | + |
| 73 | +```python |
| 74 | +# shark.py |
| 75 | + |
| 76 | +class Shark: |
| 77 | + def swim(self): |
| 78 | + print("The shark is swimming.") |
| 79 | + |
| 80 | + def be_awesome(self): |
| 81 | + print("The shark is being awesome.") |
| 82 | + |
| 83 | + |
| 84 | +if __name__ == "__main__": |
| 85 | + sammy = Shark() |
| 86 | + sammy.swim() |
| 87 | + sammy.be_awesome() |
| 88 | +``` |
| 89 | + |
| 90 | +Let’s run the program to see what it does: |
| 91 | + |
| 92 | +``` |
| 93 | +The shark is swimming. |
| 94 | +The shark is being awesome. |
| 95 | +``` |
| 96 | + |
| 97 | +The object `sammy` calls the two methods in the main body of the program, causing those methods to run. |
| 98 | + |
| 99 | + |
| 100 | +## The Constructor Method |
| 101 | +The constructor method is used to initialize data. It is run as soon as an object of a class is instantiated. Also known as the `__init__` method, it will be the first definition of a class and looks like this: |
| 102 | + |
| 103 | +```python |
| 104 | +class Shark: |
| 105 | + def __init__(self): |
| 106 | + print("This is the constructor method.") |
| 107 | +``` |
| 108 | + |
| 109 | +If you added the above `__init__` method to the Shark class in the program above, the program would output the following without your modifying anything within the `sammy` instantiation: |
| 110 | + |
| 111 | +``` |
| 112 | +This is the constructor method. |
| 113 | +The shark is swimming. |
| 114 | +The shark is being awesome. |
| 115 | +``` |
| 116 | + |
| 117 | +This is because the constructor method is automatically called when the object is created (initialized). You should use this method to carry out any initializing you would like to do with your class objects. |
| 118 | + |
| 119 | +Instead of using the constructor method above, let’s create one that uses a `name` argument that we can use to assign names to objects. We’ll set `self.name` equal to `name`: |
| 120 | + |
| 121 | +```python |
| 122 | +# shark.py |
| 123 | + |
| 124 | +class Shark: |
| 125 | + def __init__(self, name): |
| 126 | + self.name = name |
| 127 | +``` |
| 128 | + |
| 129 | +Next, we can modify the strings in our functions to reference the names, as below: |
| 130 | + |
| 131 | +```python |
| 132 | +# shark.py |
| 133 | + |
| 134 | +class Shark: |
| 135 | + def __init__(self, name): |
| 136 | + self.name = name |
| 137 | + |
| 138 | + def swim(self): |
| 139 | + # Reference the name |
| 140 | + print(self.name + " is swimming.") |
| 141 | + |
| 142 | + def be_awesome(self): |
| 143 | + # Reference the name |
| 144 | + print(self.name + " is being awesome.") |
| 145 | +``` |
| 146 | + |
| 147 | +Finally, we can set the name of the `Shark` object `sammy` as equal to `"Sammy"` by passing it as a parameter of the `Shark` class: |
| 148 | + |
| 149 | +```python |
| 150 | +# shark.py |
| 151 | + |
| 152 | +class Shark: |
| 153 | + def __init__(self, name): |
| 154 | + self.name = name |
| 155 | + |
| 156 | + def swim(self): |
| 157 | + print(self.name + " is swimming.") |
| 158 | + |
| 159 | + def be_awesome(self): |
| 160 | + print(self.name + " is being awesome.") |
| 161 | + |
| 162 | + |
| 163 | +if __name__ == "__main__": |
| 164 | + # Set name of Shark object |
| 165 | + sammy = Shark("Sammy") |
| 166 | + sammy.swim() |
| 167 | + sammy.be_awesome() |
| 168 | +``` |
| 169 | + |
| 170 | +We can run the program now: |
| 171 | + |
| 172 | +``` |
| 173 | +Sammy is swimming. |
| 174 | +Sammy is being awesome. |
| 175 | +``` |
| 176 | + |
| 177 | +We see that the name we passed to the object is being printed out. We defined the `__init__` method with the parameter `name` (along with `self`) and defined a variable within the method. |
| 178 | + |
| 179 | +Because the constructor method is automatically initialized, we do not need to explicitly call it, only pass the arguments in the parentheses following the class name when we create a new instance of the class. |
| 180 | + |
| 181 | +If we wanted to add another parameter, such as `age`, we could do so by also passing it to the `__init__` method: |
| 182 | + |
| 183 | +```python |
| 184 | +class Shark: |
| 185 | + def __init__(self, name, age): |
| 186 | + self.name = name |
| 187 | + self.age = age |
| 188 | +``` |
| 189 | + |
| 190 | +Then, when we create our object `sammy`, we can pass Sammy’s age in our statement: |
| 191 | + |
| 192 | +```python |
| 193 | +sammy = Shark("Sammy", 5) |
| 194 | +``` |
| 195 | + |
| 196 | +To make use of `age`, we would need to also create a method in the class that calls for it. |
| 197 | + |
| 198 | +Constructor methods allow us to initialize certain attributes of an object. |
| 199 | + |
| 200 | + |
| 201 | +## Working with More Than One Object |
| 202 | + |
| 203 | +Classes are useful because they allow us to create many similar objects based on the same blueprint. |
| 204 | + |
| 205 | +To get a sense for how this works, let’s add another `Shark` object to our program: |
| 206 | + |
| 207 | +```python |
| 208 | +# shark.py |
| 209 | +class Shark: |
| 210 | + def __init__(self, name): |
| 211 | + self.name = name |
| 212 | + |
| 213 | + def swim(self): |
| 214 | + print(self.name + " is swimming.") |
| 215 | + |
| 216 | + def be_awesome(self): |
| 217 | + print(self.name + " is being awesome.") |
| 218 | + |
| 219 | +if __name__ == "__main__": |
| 220 | + sammy = Shark("Sammy") |
| 221 | + sammy.be_awesome() |
| 222 | + stevie = Shark("Stevie") |
| 223 | + stevie.swim() |
| 224 | +``` |
| 225 | + |
| 226 | +We have created a second `Shark` object called `stevie` and passed the name `"Stevie"` to it. In this example, we used the `be_awesome()` method with `sammy` and the `swim()` method with `stevie`. |
| 227 | + |
| 228 | +Let’s run the program: |
| 229 | + |
| 230 | +``` |
| 231 | +Sammy is being awesome. |
| 232 | +Stevie is swimming. |
| 233 | +``` |
| 234 | + |
| 235 | +The output shows that we are using two different objects, the `sammy` object and the `stevie` object, both of the `Shark` class. |
| 236 | + |
| 237 | +Classes make it possible to create more than one object following the same pattern without creating each one from scratch. |
| 238 | + |
| 239 | + |
| 240 | +## Conclusions |
| 241 | + |
| 242 | +This tutorial went through creating classes, instantiating objects, initializing attributes with the constructor method, and working with more than one object of the same class. |
| 243 | + |
| 244 | +Object-oriented programming is an important concept to understand because it makes code recycling more straightforward, as objects created for one program can be used in another. Object-oriented programs also make for better program design since complex programs are difficult to write and require careful planning, and this in turn makes it less work to maintain the program over time. |
| 245 | + |
| 246 | + |
| 247 | +<hr /> |
| 248 | +<p id="copyright">Published under <a class="external" rel="nofollow" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">Creative Commons Attribution-NonCommercial-ShareAlike</a> license.<br/> |
| 249 | +Original author [Lisa Tagliaferri](https://lisatagliaferri.org/). Source: <https://www.digitalocean.com/community/tutorials/how-to-construct-classes-and-define-objects-in-python-3>.</p> |
0 commit comments