Methods to use lessons in Python

0
3

One of the more complicated concepts for finding your way around as a new programmer is classes and objects. However, once you know how to use classes in Python, you can create much more powerful and complex code.

Read also: What is object-oriented programming?

Read on to learn how to use classes in Python, and when you should!

Introduction to Classes in Python

For those who are unfamiliar with the concept of classes and want to learn more about how they work, read on. 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 code that describes a "data object". This is an object as you find it in the real world, only that it has no tangible presence: it only exists in concept!

Like real objects, data objects can have properties (size, weight, size, number of lives, speed), and they can have functions (move forward, jump, increase heat, erase).

In a computer game, for example, a villain 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 be. We could then call an Evil One's "shoot" function to fire projectiles, or their "destroy" function to remove them from the game.

 Python classes "width =" 1200 "height =" 675 "data attachment -id =" 1016128 "/> <img class= Also read: Using Strings in Python

The great thing about classes in Python is that they can create multiple "instances" of as ingle thing. That said, we just need to write a "BadGuy" class to create as many individual bad guys as possible!

What else could you use classes for in Python? A class can be used to describe a particular tool within a program, e.g. B. a score manager, or it can be used to describe entries in a database of clients. Anytime you want to create many examples of the same “thing”, or when you want to export complex code in a modular and easy way, classes are a good choice.

Using Classes in Python

Now that you know what to do with classes, you may be wondering how to actually use classes in Python.

Getting started is relatively easy, you have to love Python! You create a class just like you create a function, except you use "class" instead of "def". We'll then name the class, add a colon, and indent whatever follows.

(Note that classes should use capital letters to distinguish them from variables and functions. That means "BadGuy" and not "badGuy" "or" bad_guy ".)

Read Also: Defining a Python Function

So if we want to create a class that represents an enemy in a computer game, it might look like this:

BadGuy class:
Health = 5
Speed ​​= 2

This villain has two properties (variables) that describe his health and his speed of movement. Outside of this class we then have to create a BadGuy object before we can access these properties:

bad_guy_one = BadGuy ()
print (bad_guy_one.health)
print (bad_guy_one.speed)

Notice that we might as well create a bad_guy_two and a bad_guy_three and then display 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 the health of one evil, but not the other! We edited a instance of evil.

Understanding Instances

To really harness the power of classes in Python, we need to understand ] instances and constructors . If you create two bad guys from the same BadGuy class, each of them is an "instance".

Ideally, we would like to create two bad guys with different initial health. Additionally, we may wish to change this health from to of the BadGuy class.

For this we need a special type of method (function in a class), which is 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 mainly used to define the variables that relate to the specific Respectively. Instance of the object. Of course, you can do other things here as well: like sending welcome messages.

For example:

BadGuy class:

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 villain is created, we will see a message telling us that this has happened.

The constructor method is always called __ init__ and always has "self" as the first argument. You can then pass in any other arguments that you want to use to set up your object when you initialize it for the first time.

The term "self" simply means that everything you do relates to that specific instance of the object.

Use of functions in classes in Python

As already mentioned, a function in Python is technically called a method.

We can create methods within a class the way we normally create functions, but there are two different types of methods:

  • Instance methods
  • Static methods

An instance method only affects the instance of the object to which it belongs. Hence, we can use this as a more convenient way to inflict damage to individual enemies:

BadGuy class:

def __init __ (self, health, speed):
print ("A new badguy has been created!")
Self-health = health
Self-speed = speed

def shot_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 in such a way that it acts globally. To create static methods, we remove the "self" argument and use the decorator @staticmethod just above the method name instead.

In the following example we create a static method to generate a random number, then we subtract that amount from the enemy's health. The method doesn't have to specifically reference the instance of that object, so it can simply behave like a normal function that we can access when using the class.

BadGuy class:

def __init __ (self, health, speed):
print ("A new badguy has been created!")
Self-health = health
Self-speed = speed

@staticmethod
def random_generator ():
import at random
n = random.randint (1, 5)
return n

def shot_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 at any point in our code we can also use the following line to get a random number:

print (bad_guy_two.random_generator ())

If for some reason we want Um To prevent this, we just have to put a double underscore in front of our method name.

@ staticmethod
def __random_generator ():

How to create a private method in Python and prevent us from accessing the method outside of this class.

Close

Finally, the last thing you might want to do is put your class in a separate file. That way, your code stays tidy and you can easily share the classes you've created between projects.

Simply save the class in a new file:

BadGuy class:

def __init __ (self, health, speed):
print ("A new badguy has been created!")
Self-health = health
Self-speed = speed

@staticmethod
def __random_generator ():
import at random
n = random.randint (1, 5)
return n

def shot_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.

You can now access the class and all of its properties and methods from any other Python script:

BadGuy import

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! How To Use Classes In Python! This is an extremely valuable skill that will allow you to build all kinds of amazing things in the future.

At this point, you are probably ready to take your skills to the next level. In that case, try one of these amazing online Python courses:

Coding With Python: The Budding Developer Training gives you a comprehensive introduction to Python that takes you from the basics of coding to programming up. Level skills that will prepare you for a career in Python development. This course typically costs $ 690 but is available to Android Authority readers for only $ 49!

Alternatively, check out our comprehensive beginner's guide to Python to see how classes fit into the bigger picture:

LEAVE A REPLY

Please enter your comment!
Please enter your name here