Python is an object-oriented programming language. It means almost everything is an object. When becoming a Python developer, it’s crucial to learn what is a Python class and how to use it to create those objects.
A Python class is a blueprint for creating objects.
For example, here is a simple class Person
, that has an attribute name
:
class Person: name = "Sofie"
Now you can create a Person
object from the class by:
girl = Person()
An object is also known as an instance of a class. The process of creating objects from a class is called instantiation.
You can use a class to instantiate different objects that all represent the class. For example, you can create multiple persons with different names.
How to Crete a Class in Python
To create a new Python class, use the class
keyword.
Here is the syntax for defining a class in Python:
class ExampleClass: pass
Now, every piece of code you write into this block belongs to that class.
For now, we are going to pass the implementation of the class, as we will return to it later on.
How to Use a Python Class
In the previous section, you learned the syntax for creating a class in Python. But how can you use this class?
The answer is you can create, or more formally, instantiate objects of the class.
Creating an instance of the above ExampleClass
looks like this:
obj = ExampleClass()
Now obj
is a Python object that represents the ExampleClass
. It thus has all the behavior described in the class. However, now the ExampleClass
is empty, thus you can not do much with its representative objects.
In the next section, we are going to learn how to associate properties and behavior with the class. This way you can put your class into use.
Attributes and Methods in a Python Class
A bare class is not much of use. To benefit from using classes, you need to associate some behavior with them.
For example, a Person
class could store info about the person and a method that introduces it.
To associate properties and behavior to a class, you need to create attributes and methods in the class.
Let’s first have a look at how to create class attributes in Python.
Attributes in a Class
Attributes in classes are properties that are present in the class and its objects. For example, a Fruit class could have a color
attribute.
To create attributes in a class, declare them as variables in the class.
For example, let’s create a Fruit
class with a color
attribute:
class Fruit: color = "Yellow"
(Keep in mind you can add as many attributes to your class as you want.)
If you now instantiate a Fruit
object based on the above Fruit
class, you can access its color
property using the dot notation.
For example, let’s create a Fruit
object called some_fruit
and display its color
by printing it into the console:
some_fruit = Fruit() print(some_fruit.color)
Output:
Yellow
Now, the color of some_fruit
is "Yellow"
because that’s what you defined in the class. But you can change it for this particular object if you wish to.
For instance, let’s turn some_fruit
to red:
some_fruit.color = "Red" print(some_fruit.color)
Output:
Red
This change in color
does not affect the Fruit
class. Instead, it only changes the object, as you can see.
Now that you understand what class attributes are in Python, let’s take a look at methods in classes.
Methods in a Python Class
A function inside a class is known as a method. A method assigns behavior to the class.
Usually, a method uses the attributes (or the other methods) of the class to perform some useful task. For example, a Weight
class could have a kilograms
attribute. In addition, it can have a to_pounds()
method, that converts the kilograms
to pounds.
To create a method for your class in Python, you need to define a function in it.
As mentioned, the method needs to access the attributes of the class. To do it, the method has to accept an argument that represents the class itself.
Let’s put it all together in a form of a simple example:
Let’s create a Person
class and define an introduce()
method to it. This makes it possible for each Person
object to introduce themselves by calling person.introduce()
:
class Person: name = "Sophie" def introduce(self): print("Hi, I'm", self.name)
If you now look at the introduce()
method, you can see it takes one argument called self
. This is there because as mentioned earlier, the class needs to be able to access its own attributes to use them. In this case, the person needs to know the name of itself.
Now you can create a person objects and make them introduce themselves using the introduce()
method.
For instance:
worker = Person() worker.name = "Jack" worker.introduce()
Result:
Hi, I'm Jack
Wonderful! You know the basics of defining a class and creating objects that contain attributes and some useful behavior.
But in the above example, the name
of a Person
is always Sophie
to begin with. When you create a person object, you need to separately change its name
if you want to. Even though it works, it is not practical.
A better for instantiating objects would be to directly give them a name upon creation:
dude = Person("Jack")
Instead of first creating an object and then changing its name on the next line:
dude = Person() dude.name = "Jack"
To do this, you need to understand class initialization and instance variables. These give you the power to instantiate objects with unique attributes instead of separately modifying each object.
Class Initialization in Python
As you saw in the previous section, creating a person object with a unique name is only possible this way:
dude = Person() dude.name = "Jack"
But what you actually want is to be able to do this instead:
dude = Person("Jack")
This is possible and it is called class initialization.
To enable class initialization, you need to define a special method into your class. This method is known as a constructor or initializer and is defined with def __init__(self):
.
Every class can be provided with the __init__()
method. This special method runs whenever you create an object.
You can use the __init__()
method to assign initial values to the object (or run other useful operations when an object is created).
The __init__()
method is also known as the constructor method of the class.
In the Person
class example, all the Person objects have the same name “Sophie”
.
But our goal is to be able to create persons with unique names like this:
worker = Person("Jack") assistant = Person("Charlie") manager = Person("Sofie")
To make it possible, implement the__init__()
method in the Person class:
class Person: def __init__(self, person_name): self.name = person_name
Now, let’s test the Person
class by instantiating person objects:
worker = Person("Jack") assistant = Person("Charlie") manager = Person("Sofie")
print(worker.name, assistant.name, manager.name)
Output:
Jack Charlie Sofie
Let’s inspect the code of the Person
class to understand what is going on:
- The
__init__()
method accepts two parameters:self
andperson_name
self
refers to thePerson
instance itself. This parameter has to be the first argument of any method in the class. Otherwise, the class does not know how to access its properties.person_name
is the name input that represents thename
you give to a new person object.- The last line
self.name = person_name
means “Assign the inputperson_name
as thename
of this person object.”
self.name
is an example of an instance variable. This means that self.name
is an instance-specific (or object-specific) variable. You can create Person
objects each with a different name
.
To Recap
Initialization makes it possible to assign values to an object upon creation. The __init__()
method is responsible for the initialization process. The method runs whenever you create a new object to set it up. This way you can for example give a name to your object when creating it.
Conclusion
In Python, a class is an outline for creating objects.
A Python class can store attributes and methods. These define the behavior of the class.
Also, you can initialize objects by implementing the __init__()
method in the class. This way you can create objects with unique values, also known as instance variables without having to modify them separately.
Thanks for reading. Happy coding!