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.
One of the most important concepts in object-oriented programming is the distinction between classes and objects, which are defined as follows:
These are used to create patterns (in the case of classes) and then make use of the patterns (in the case of objects).
In this tutorial, 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.
You should have Python 3 installed and a programming environment set up on your computer or server. If you don’t have a programming environment set up, you can refer to the installation and setup guides for a local programming environment or for a programming environment on your server appropriate for your operating system (Ubuntu, CentOS, Debian, etc.)
Classes are like a blueprint or a prototype that you can define to use to create objects.
We define classes by using the class
keyword, similar to how we define functions by using the def
keyword.
Info: To follow along with the example code in this tutorial, open a Python interactive shell on your local system by running the python3
command. Then you can copy, paste, or edit the examples by adding them after the >>>
prompt.
Let’s define a class called Shark
that has two functions associated with it, one for swimming and one for being awesome:
class Shark:
def swim(self):
print("The shark is swimming.")
def be_awesome(self):
print("The shark is being awesome.")
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.
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.
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.
Creating the Shark
class above provided us with a blueprint for an object.
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.
We’ll make a Shark
object called sammy
:
sammy = Shark()
Here, we initialized the object sammy
as an instance of the class by setting it equal to Shark()
.
Now, let’s use the two methods with the Shark
object sammy
:
sammy = Shark()
sammy.swim()
sammy.be_awesome()
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.
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.
When we call the methods, however, nothing is passed inside the parentheses, the object sammy
is being automatically passed with the dot operator.
Let’s add the object within the context of a program:
class Shark:
def swim(self):
print("The shark is swimming.")
def be_awesome(self):
print("The shark is being awesome.")
def main():
sammy = Shark()
sammy.swim()
sammy.be_awesome()
if __name__ == "__main__":
main()
Let’s run the program to see what it does:
- python shark.py
OutputThe shark is swimming.
The shark is being awesome.
The object sammy
calls the two methods in the main()
function of the program, causing those methods to run.
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:
class Shark:
def __init__(self):
print("This is the constructor method.")
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:
OutputThis is the constructor method.
The shark is swimming.
The shark is being awesome.
This is because the constructor method is automatically initialized. You should use this method to carry out any initializing you would like to do with your class objects.
Instead of using the constructor method above, let’s create one that uses a name
variable that we can use to assign names to objects. We’ll pass name
as a parameter and set self.name
equal to name
:
class Shark:
def __init__(self, name):
self.name = name
Next, we can modify the strings in our functions to reference the names, as the following:
class Shark:
def __init__(self, name):
self.name = name
def swim(self):
# Reference the name
print(self.name + " is swimming.")
def be_awesome(self):
# Reference the name
print(self.name + " is being awesome.")
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:
class Shark:
def __init__(self, name):
self.name = name
def swim(self):
print(self.name + " is swimming.")
def be_awesome(self):
print(self.name + " is being awesome.")
def main():
# Set name of Shark object
sammy = Shark("Sammy")
sammy.swim()
sammy.be_awesome()
if __name__ == "__main__":
main()
We can run the program now:
- python shark.py
OutputSammy is swimming.
Sammy is being awesome.
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 the self
keyword) and defined a variable within the method.
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.
If we wanted to add another parameter, such as age
, we could do so by also passing it to the __init__
method:
class Shark:
def __init__(self, name, age):
self.name = name
self.age = age
Then, when we create our object sammy
, we can pass Sammy’s age in our statement:
sammy = Shark("Sammy", 5)
To make use of age
, we would need to also create a method in the class that calls for it.
Constructor methods allow us to initialize certain attributes of an object.
Classes are useful because they allow us to create many similar objects based on the same blueprint.
To get a sense for how this works, let’s add another Shark
object to our program:
class Shark:
def __init__(self, name):
self.name = name
def swim(self):
print(self.name + " is swimming.")
def be_awesome(self):
print(self.name + " is being awesome.")
def main():
sammy = Shark("Sammy")
sammy.be_awesome()
stevie = Shark("Stevie")
stevie.swim()
if __name__ == "__main__":
main()
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
.
Let’s run the program:
- python shark.py
OutputSammy is being awesome.
Stevie is swimming.
The output shows that we are using two different objects, the sammy
object and the stevie
object, both of the Shark
class.
Classes make it possible to create more than one object following the same pattern without creating each one from scratch.
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.
Object-oriented programming is an important concept to understand because it enables code reuse, 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.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Python is a flexible and versatile programming language that can be leveraged for many use cases, with strengths in scripting, automation, data analysis, machine learning, and back-end development. It is a great tool for both new learners and experienced developers alike.
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.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Sign up for Infrastructure as a Newsletter.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Thank you Lisa. Tutorials on Digital Ocean are among the clearest, most elegant, and most to the point. Your tutorial should be an example in clear thinking and communication.
My method is like this. If am I right or wrong?
class Mobile: def init(self,name,model): self.name = name self.model = model
class MobileStore: def init(self): self.mobiles = []
oneplus = Mobile(‘one plus 6’, ‘s9’)
samsung = ‘samsung galaxy s6’
mobostore = MobileStore()
mobostore.add_mobile(samsung) #raising error
print(mobostore.mobiles)
mobostore.add_mobile(oneplus) mobophones = mobostore.mobiles print(mobophones[0].model)
@TheWrongCoder
When you create an object out of the class, you use the brackets, but when you define a new class name, you do not use brackets.
However, I understand why you asked that question. According to this site: http://www4.ncsu.edu/~kaltofen/courses/Languages/PythonExamples/python-lectures/_build/html/lectures/three.html:
class Name('object')
is preferred overclass Name
because the author of that site claims the latter will not work in Python 3.X (3 or above). I ran a sample code using both styles and had no problems–that is, both work. But Python Zen dictates there be only ONE way to do something in Python, and ‘simple is better than complex’, hence the no brackets version makes sense at least from the point of view of readability and programmer efficiency.More concretely:
Here is when we define a new class called Food:
Now Food is too general. Suppose I order some Food. I cannot say I want Food to the waitress, right? so I create a food object but this time I need brackets for the class name:
But this is not very helpful. What kind of pizza did I have in mind?
So an 18-inch spicy Margarita for 20$. Thus, including brackets when we created a new object out of the general class was holding all that info inside it, whereas the original name of the class when we began to define it does not cause confusion and can be written without the brackets–especially to differentiate it from a function (as functions need brackets for their arguments).
Haaaaaaaaaaaa teacher,why the class name has no opening and closing curve brackets ?.Great content ,explained in very easy and simple words.👍
@ltagliaferri, hi there: