Method
Published Oct 21, 2021Updated Oct 26, 2022
Contribute to Docs
Classes can be broken into two core parts:
- The data that is attributed to a class’s members or properties.
- The behaviors that are defined or inherited in the class.
Methods are the “behavior” part of the class. When an instance variable is created from a class, it has access to the class’s associated methods. Methods can accept parameters (sometimes they’re called “arguments”) and can return a result.
In object-oriented programming, methods promote reusability and keep functionality encapsulated inside an object.
Example
In the Python example below, a class for a character in a game, Character
, is defined with certain behaviors. The character can:
- Introduce themselves via
.introduceSelf()
. - Move left given an integer amount via
.moveLeft()
. - Move right given an integer amount via
.moveRight()
.
class Character:def __init__(self, name, movex):self.name = "Player" # Character's nameself.movex = 0 # Character's starting positiondef introduceSelf(self):# Print out an introduction phraseprint(f"Hello! I'm {self.name}.")def moveLeft(self, x):# Move the character left by x pixelsself.movex -= xdef moveRight(self, x):# Move the character right by x pixelsself.movex += x
Now, when an instance of Character
is created, the game character can introduce themselves, move left, or move right.
Methods in Different Languages
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn more on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours