One of the more complicated concepts to get your head around as a new programmer is classes and objects. Once you know how to use classes in Python though, you will be ready to build significantly more powerful and complex code.
Also read: What is object oriented programming?
Read on to learn how to use classes in Python, and when you should!
Introducing classes in Python
For those that are unfamiliar with the concept of classes and who want to learn 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 a class? A class is a piece of code that describes a “data object.” This is an object just like you find in the real world, except that it has no tangible presence: it only exists in concept!
Like real objects though, data objects can have properties (size, weight, height, number of lives, speed), and they can have functions (move forward, jump, turn up the heat, delete).
In a computer game, for instance, a bad guy could be described in the code as a data object. This would keep track of how much health the bad guy had, where it was in relation to the player, and how aggressive it would behave. We could then call a bad guy’s “shoot” function to fire projectiles, or their “destroy” function to remove them from the game.
(Except that we call functions “methods” when they appear inside classes in Python!)
You’d then simply use your graphics routines 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 similarly: except instead of storing one piece of data as an integer, you are storing custom information about an object you conceived.
Also read: How to use strings in Python
The great thing about classes in Python, is that they can create multiple “instances” of a single thing. That means we only need to write one “BadGuy” class in order to create as many individual bad guys as well like!
What else might you use classes in Python for? A class could be used to describe a particular tool within a program, such as a score manager, or it could be used to describe entries in a database of clients. Any time you want to create lots of examples of the same “thing,” or any time you want to handle complex code in a modular and easily-exported fashion, classes are a great choice.
How to use classes in Python
So, now you know what the deal with classes is, you may be wondering how to actually use classes in Python.
Getting started is relatively simple, got to love Python! You will create a class in just the same way you create a function, except you will use “class” instead of “def.” We then name the class, add a colon, and indent everything that follows.
(Note that classes should use upper-case camel case to differentiate them from variables and functions. That means “BadGuy” and not “badGuy” or “bad_guy.”)
Also read: How to define a function Python
So, if we wanted to create a class that would represent an enemy in a computer game, it might look like this:
class BadGuy: health = 5 speed = 2
This bad guy has two properties (variables) that describe its health and its movement speed. Then, outside of that class, we need to create a BadGuy object before we can access those properties:
bad_guy_one = BadGuy() print(bad_guy_one.health) print(bad_guy_one.speed)
Note that we could just as easily create a bad_guy_two and a bad_guy_three, then show each of their properties!
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 have changed the value of one bad guy’s health, but not the other! We have edited one instance of the bad guy.
Understanding instances
In order to really tap into the power of classes in Python though, we need to understand instances and constructors. If you create two bad guys from the same BadGuy class, then each one of these is an “instance.”
Ideally, we might want to create two bad guys with different starting health. Moreover, we might want to alter that health from within the BadGuy class.
To do this, we need a special type of method (function in a class) called a “constructor.”
The constructor is called as soon as you create a new instance of an object (when you “instantiate” the object) and is used predominantly to define the variables as they relate to that specific instance of the object. Though, of course, you can do other things here too: such as sending welcome messages.
So, for example:
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). Each time a new bad guy is created, a message pops up to tell us that has happened.
The constructor method is always called __init__ and will always have “self” as the first argument. You can then pass whatever other arguments you want to use in order to set-up your object when you first initialize it.
The term “self” simply means that whatever you’re doing is referring to that specific instance of the object.
How to use functions in classes in Python
As mentioned, a function in Python is technically referred to as a method.
We can create methods within a class just as we normally create functions, but there are two different types of method:
- Instance methods
- Static methods
An instance method will only affect the instance of the object it belongs to. Thus, we can use this as a more convenient way to damage individual enemies:
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 act globally. To make static methods, we remove the “self” argument and instead use the @staticmethod decorator just above the method name.
In the following example, we create a static method to generate a random number, then we subtract this amount from the enemy’s health. The method doesn’t need to specifically relate to the instance of that object, so it can simply act like a normal function we gain access to when we use the class.
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 also use the following line at any point in our code to get a random number:
print(bad_guy_two.random_generator())
If, for whatever reason, we want to prevent this from happening then we simply need to prefix our method name with a double underscore.
@staticmethod def __random_generator():
This is how to create a private method in Python, and it will prevent us from accessing the method outside of that class.
Closing up
Finally, the last thing you might want to do is place your class in a separate file. This will keep your code tidy, while also letting you easily share the classes you’ve made between projects.
To do this, simply save the class as it is in a new file:
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 also needs to be saved in the same 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:
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 future.
At this point, you are probably ready to take your skills to the next level. In that case, why not try one of these amazing online Python courses:
Coding with Python: Training for Aspiring Developers will provide you with a comprehensive introduction to Python that will take you from the basics of coding to high-level skills that prepare you for a career in Python development. This course usually costs $690 but is available to Android Authority readers for just $49!
Alternatively, you can see how classes fit into the big picture by checking out our comprehensive beginners’ guide to Python:
from Android Authority https://ift.tt/3gmhRwb
No comments:
Post a Comment