Methods (OOP)
A method is the equivalent of a function in object-oriented programming. A noun is to a verb what a variable is to a method — the methods are the actions that perform operations on a variable. A method accepts parameters as arguments, manipulates these, and then produces an output when the method is called on an object. Methods are similar to functions, but methods are also classified according to their purpose in the class design. In classes, variables are called attributes, so methods often operate on attributes.
To fully appreciate object-oriented programming, you should be familiar with the basics of programming — check out the see also to see some suggested pages about basic programming.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
Using Python, which of the following methods could be added to the class IceCream
to print out the size of the order based on the number of scoops where 1 to 3 scoops is a small, 4 to 5 is a medium, and more than that is
a large.
1 2 3 4 5 6 7 |
|
1 2 3 4 5 6 7 |
|
1 2 3 4 5 6 7 |
|
1 2 3 4 5 6 7 |
|
(ignore the fact that these functions may return None
along with the size printed)
Methods
Methods are like functions or subroutines or algorithms that are used inside classes. Methods can include for loops, while loops, and any other programming components. Methods can manipulate attributes associated with an object. There are three main types of methods: interface methods, constructor methods, and implementation methods. Most beginner programmers are familiar with implementation methods. For example, in Python, appending to a list takes a method append
and applies it to a list object.
1 2 3 4 5 6 7 |
|
When calling a method on an object in Python, the format is instanceName.method()
. Some beginners forget to add the parentheses after a method, so watch out for that. Sometimes it is necessary to include arguments to a method call (like in append in the example above).
In Python, the first parameter for methods is self
. The self
parameter is used to create member variables. Inside a class, we initialize any variables that might have different values depending on the specific instance of the class as self.VariableName
.
Interface Methods
Interface methods are the methods that have the purpose of providing an interface for an object with the external environment, for example, other objects' methods, data input from a user, data from another object, or anything that's not inside that very same object.
One of the principles of object-oriented design is encapsulation. Encapsulation is the technique of building an object to be a capsule containing all of its data and methods inside itself. However, an object that is isolated from everything is just plain useless, it should be a part of a bigger system. That's when interface methods come in: they provide the minimum necessary interface for that object to get external input and provide output so it can indeed be a part of a bigger system while also being a smaller system on itself.
For example, it is a very good object-oriented practice to define a getter and a setter method for an attribute, most notably to security and code integrity reasons. A getter gets the variable from the user input, and the setter assigns the variable as it will be used throughout the class. Getters and setters are methods which provide internal attributes access to external agents in an indirect way. Let's see how they are implemented:
Getter & Setter Interface Methods in Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20class Square(object): def __init__(self, sideLength): self.sideLength = sideLength # Getter: def getSideLength(self): return self.sideLength # Setter: def setSideLength(self,sideLength): self.sideLength = sideLength square = Square(10.0) print square.getSideLength() # prints 10.0 to the screen square.setSideLength(3.0) print square.getSideLength() # prints 3.0 to the screen
This code snippet defines a Square
class which will have instances with a sideLength
attribute accessible through the getter method getSideLength
which will provide that attribute's value and through the setter method setSideLength
which will provide a way to alter that attribute's value.
Then, an instance of the Square
class is created with an initial value for sideLength
equaling 10.0 and this instance gets assigned to the square
variable. The value of the sideLength variable is then printed on the screen, then the value of sideLength is updated and finally, the updated value of the sideLength
variable is printed to the screen.
The __init__()
Python method can be confusing for beginners to object-oriented programming. These are really just another type of method called a constructor.
Constructor
A constructor is used to instantiate a class, which is what effectively creates an object (remember that a class is a blueprint for an object, and an object is an instance of a class). They are usually either named after the class (such as in Java and C#) or named after a keyword (such as in Python and Ruby). The parameters of a constructor method, when present, are usually the initial values to be assigned to some or all of the attributes of that object. You've seen an example of a constructor which assigns attributes in the example in the previous section. Let's see an example of a constructor which does not take any parameters and instead initializes the object attributes to some default values:
Constructor in Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19class Square(object): # Constructor: def __init__(self): self.sideLength = 5.0 def getSideLength(self): return self.sideLength def setSideLength(self,sideLength): self.sideLength = sideLength square = Square() # invokes the constructor method print square.getSideLength() # prints 5.0 to the screen square.setSideLength(3.0) print square.getSideLength() # prints 3.0 to the screen
The program's structure is basically the same, except that the constructor now takes no parameters and returns the default value when the getter is called for an attribute which did not have its value individually set.
Also, note that not only the constructor implementation needs to obey some language-specific conventions, but the constructor invoking as well. In Java, the constructor is invoked by adding the keyword 'new' before calling the constructor with (or without) its parameters. In Python, the constructor is invoked by passing parameters to the class (this will actually trigger the__init__
method).
Implementation Methods
The implementation method is the one that most resembles a standard procedural function. Like the name suggests, this is a method that will actually implement functionality to the object. These are the typical methods a programmer would write into their code. This is usually done by manipulating the object's attributes and provides some output (or alters some internal attribute in a specific way without providing any immediate output, etc.). Let's implement the outputArea
functionality in out Square
object:
Implementation Methods in Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21class Square(object): # Constructor: def __init__(self): self.sideLength = 5.0 def getSideLength(self): return self.sideLength def setSideLength(self,sideLength): self.sideLength = sideLength # Implemented functionality: def outputArea(): return self.getSideLength() * self.getSideLength() square = Square() square.setSideLength(3.0) print square.outputArea() # prints 9.0 to the screen
So, what's happening here? The output of the outputArea()
method displays the area of a square with a side length equal to that Square's sideLength attribute. The basic guideline for a method internal to an object is to operate inside its data to provide actual functionality. Any method that has a more general functionality not restricted to a single class (or class hierarchy) is usually defined inside a module (think of a module as a collection of methods designed to provide functionality that can be applied in a lot of different classes).
If the Square's sideLength attribute was 4.0 instead of 3.0, the output would be 16.0 instead of 9.0. The method is also not restricted to just performing some closed operation on its attributes, we could manipulate the output using both the object's attributes and some arbitrary parameter, like so:
New implementation of outputArea method in Python:
1 2 3 4def outputAreaTimesN(self, n): return (self.getSideLength() * self.getSideLength()) * n print square.outputAreaTimesN(2) # prints 18.0 to the screen
Let's say we have a video game where the player controls a dragon. The dragon has many characteristics — it can breathe fire, it can fly, it has a color, it gets points when it destroys villages, etc. What are some methods that might have? Another character in the game is a knight — what could some methods for the knight be?
The dragon could have a
fly
method that sets it actions to flying and updates its speed and how high it is flying. The dragon could have a fire breathing method that updates its status to a fighting, fire-breathing mode. There could be a method that updates its score when it gains points. The dragon could have a method that updates its health when it is attacked or when it heals.The knight might have methods that update how fast he is running, how many points he is earning, or changes his health. He could have a method that allows him to change his weapon or armor.
See Also
Basic Programming Pages