One of the most complex concepts to get your head around as a new programmer is classes and objects. Once you know how to use classes in Python, you’ll be ready to build more powerful and complex code.
Also Read: What is Object Oriented Programming?
Read on to learn how and when to use classes in Python!
Introducing classes in Python
For those who are unfamiliar with the concept of classes and want to know more about how they work, keep reading. If you just want the syntax for classes in Python, you can skip to the next section!
So what is this class? A class is code that defines a “data object”. This is exactly what you would find in the real world, except it has no real existence: it exists only in concept!
Like real objects, data objects can have properties (size, weight, height, number of lives, speed), and they can have functions (move forward, jump, add heat, delete).
For example, in a computer game, a villain can be defined as a data object in the code. This keeps track of how much health the bad guy has, where he is in relation to the player, and how aggressive he will be. Then we can remove the bad guy’s “shoot” function to fire the projectors or their “destroy” function from the game.
(Except we call functions “methods” when they appear inside classes in Python!)
You simply use your graphics routine to draw those bad guys to the screen based on the information provided by the class.
When to use Python classes
If you know how to use variables in Python, this works the same way: except you’re storing data as an integer, you’re storing custom data about the object you’re thinking of.
Also Read: How to use strings in Python
The great thing about classes in Python is that they can create multiple “instances” of an object. That means we only need to write one “BadGuy” class to create as many individual bad guys as you like!
What else can you use classes for in Python? A class can be used to define a specific tool in a program, such as a results manager, or entries in a customer database. Classes are a great choice when you want to create multiple instances of the same “object” or anytime you want to contain complex code in a modular and easily exportable fashion.
How to use classes in Python
So, now that you know what the deal is with classes, you might be wondering how to use classes in Python.
Getting started is relatively easy, I’m starting to love Python! You create a class the same way you create a function, except you use “class” instead of “def”. Then we give the name of the section, add a colon and enter everything that follows.
(Note that classes must be separated from variables and functions by using an uppercase camel case. This means “BadGuy”, not “badGuy” or “bad_guy”.)
Also Read: How to define a Python function
So, if we want to create a class that represents an enemy in a computer game, it might look like this.
Code
class BadGuy:
health = 5
speed = 2
This bad guy has two attributes (variables) that define his health and movement speed. Then, outside of that class, we need to create a BadGuy object before accessing those properties:
Code
bad_guy_one = BadGuy()
print(bad_guy_one.health)
print(bad_guy_one.speed)
Notice that we can create just like bad_two and bad_guy_three and display each of their properties!
Code
bad_guy_one = BadGuy()
bad_guy_two = BadGuy()
print(bad_guy_one.health)
print(bad_guy_two.health)
bad_guy_one.health -= 1
print(bad_guy_one.health)
print(bad_guy_two.health)
Here, we’ve changed the health value of one bad guy, but not the other! We fixed one. for example From a bad person.
Understanding examples
Although to truly understand the power of classes in Python, we need to understand Conditions And Developers. If you create two bad guys from the same BadGuy class, each of these is an “instance”.
Ideally, we want to create two bad guys with different starting health. Also, we want to change that health from here in The BadGuy episode.
To do this we need a special type of method (a function inside the class) called “constructor”.
A constructor is called as soon as you create a new instance of an object (when you “make” the object) and is commonly used to define the variables associated with it. Certain Example of the thing. Although, of course, you can do other things here too, such as sending a welcome message.
Code
class BadGuy:
def __init__(self, health, speed):
print("A new badguy has been created!")
self.health = health
self.speed = speed
bad_guy_one = BadGuy(5, 2)
bad_guy_two = BadGuy(3, 5)
print(bad_guy_one.health)
print(bad_guy_two.health)
This code creates two bad guys. One is strong but slow (health 5, speed 2), the other is weak but fast (3, 5). Every time a new bad guy is created, a message will pop up telling us what happened.
The constructor method is always called __in__ And it will always have “self” as the first argument. You can pass any other arguments you want to use to set the object when you initialize it for the first time.
The word “self” simply means anything you do. Certain Example of the thing.
How to use functions in classes in Python
As mentioned, a function in Python is technically called a method.
We can create methods in a class just like we create functions normally, but there are two different types.
- Example methods
- Static methods
An instance method only affects an instance of its object. So, we can use this as a more convenient way to damage enemies:
Code
class BadGuy:
def __init__(self, health, speed):
print("A new badguy has been created!")
self.health = health
self.speed = speed
def shoot_badguy(self):
self.health -= 1
print("Ouch!")
bad_guy_one = BadGuy(5, 2)
bad_guy_two = BadGuy(3, 5)
def display_health():
print(bad_guy_one.health)
print(bad_guy_two.health)
display_health()
bad_guy_one.shoot_badguy()
display_health()
A static method, on the other hand, is designed to work globally. To make static methods, we remove the “self” argument and use the @static method Decoration above the method name.
In the following example, we will create a static method to generate a random number, and then subtract this amount from the enemy’s health. The method doesn’t need to match an instance of that object specifically, so it can act like a normal function when we use the class.
Code
class BadGuy:
def __init__(self, health, speed):
print("A new badguy has been created!")
self.health = health
self.speed = speed
@staticmethod
def random_generator():
import random
n = random.randint(1, 5)
return n
def shoot_badguy(self):
self.health -= self.random_generator()
print("Ouch!")
bad_guy_one = BadGuy(5, 2)
bad_guy_two = BadGuy(3, 5)
def display_health():
print(bad_guy_one.health)
print(bad_guy_two.health)
display_health()
bad_guy_one.shoot_badguy()
display_health()
Note that we can use the following line anywhere in our code to get a random number.
Code
print(bad_guy_two.random_generator())
If we want to prevent this from happening for any reason, we just need to double-underline our method name.
Code
@staticmethod
def __random_generator():
This is how to create a private method in Python, and prevent us from accessing the method outside of that class.
Closing
Finally, the last thing you can do is save your class in a separate file. This keeps your code clean, and lets you easily share learnings between projects.
To do this, simply save the class as is in a new file:
Code
class BadGuy:
def __init__(self, health, speed):
print("A new badguy has been created!")
self.health = health
self.speed = speed
@staticmethod
def __random_generator():
import random
n = random.randint(1, 5)
return n
def shoot_badguy(self):
self.health -= self.__random_generator()
print("Ouch!")
Be sure to give the file the same name as the class. In this case: “BadGuy.py” is the name of the file. It should also be placed in the directory where you save your main Python file.
Now you can access the class and all its properties and methods from any other Python script:
Code
import BadGuy
bad_guy_one = BadGuy.BadGuy(5, 2)
bad_guy_two = BadGuy.BadGuy(3, 5)
def display_health():
print(bad_guy_one.health)
print(bad_guy_two.health)
display_health()
bad_guy_one.shoot_badguy()
display_health()
And there you have it! That’s how to use classes in Python! This is an extremely valuable skill and one that will allow you to build all kinds of amazing things in the future.
At this point, you’re ready to take your skills to the next level. If so, why not check out our guide to the best online Python courses.
Coding in Python: Training for Aspiring Developers gives you a comprehensive introduction to Python, from the basics of Python development to advanced skills that prepare you for a career in Python development. This course usually costs $690 but is available for that. Android Authority. Readers for only $49!
Alternatively, you can check out our comprehensive Python beginners guide to see how the lessons fit into the bigger picture.
Don’t miss to subscribe to the monthly newsletter below for more developer news, features and tutorials for Android Authority!