How to Create and Call a Method in a Class in Python 


               


How to Create and Call a Method in a Class in Python



Python


In this article, we show how to create and call a method in a class in Python.

So, if you create a class and define a method in that class, that method is specific to the class.

So that method will only work for instances of that class.

Let's go over code below that contains a method for the class animals. We then create an instance of the animals class and invoke the method.



What we have done is we created a class named animals. We assigned it the attributes type equals "land" and color equals "green".

We then created a method called get_color(). Within a method in a class in Python, you want to pass in the parameter, self, into the method. self is a reference that when you name an object, it is referring to itself, one of its attributes. It's pretty self-descriptive and self-explanatory, when you think about it.

In this method, we return self.color

What self.color does is it returns whatever value the color attribute is set to for whatever object you are dealing with.

Since we create the color attribute to be "green" in the animals class, an instance of the animals class that we create is also going to have "green" be the value of the color attribute.

Therefore, when we create an instance of the animals class, animal1, and invoke the get_color() method on the object, animal1, it returns 'green' as output.

We invoke a method by first typing in the name of the object we are referencing, followed by a dot (.), followed by the method with parenthesis. So we call the get_color() method on the animal1 object by the line, animal1.get_color()

And you don't just have to return singularly the attribute.

You can return anything as output.

For example, if we wanted to create with the get_color() method, "This animal is the color (value)", the following code below would do so.



So, now we've modified the code so that a sentence is returned instead of just the attribute alone.

So this just gives you a rundown of methods in classes in Python, how to call them, and what you can do with them.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...