WhatIs.com

method (in object-oriented programming)

By Robert Sheldon

What is a method (in object-oriented programming)?

In object-oriented programming (OOP), a method is a programmed procedure that is defined as part of a class and is available to any object instantiated from that class. Each object can call the method, which runs within the context of the object that calls it. This makes it possible to reuse the method in multiple objects that have been instantiated from the same class.

The objects remain independent of each other throughout the application's runtime. If one of the objects calls a method, that method can access only the data known to the object, ensuring data integrity across the application. A class -- and thus, an object -- can contain multiple methods. Each of those methods can be invoked through the class, although they all operate independently from each other.

The way in which methods are defined, referenced and invoked differs from one OOP language to the next, but the basic principles are generally the same. Once a class and its methods have been defined, an application can reference the class, either directly from within the same file or by pointing to the class where it resides. For example, an application might import a package or module that includes the class, and then use its methods within the application code. The application can then instantiate objects based on the class and access the class's methods.

Example of how methods work in object-oriented programming

The following Python scripts provide a basic example of how classes and methods work in an OOP language. The first script creates a simple class named Author, which contains three methods.

class Author:

  def __init__(self, self, first='', middle='', last=''):
    self.first = first
    self.middle = middle
    self.last = last

  def get_name(self):
    names = [self.first, self.middle, self.last]
    full_name = ' '.join(filter(None, names))
    return full_name

  def update_name(self, first='', middle='', last=''):
    self.first = first
    self.middle = middle
    self.last = last
    return 'Updated name: ' + self.get_name()

The first method, __init__, is a special method that serves as a constructor in Python classes. The method enables an application to instantiate an object based on the Author class, using the parameters first, middle and last. In this way, an application can pass in the names when creating the object. The __init__ method is commonly included in Python class definitions. Other languages have comparable structures for instantiating an object based on a class.

The second method, get_name, retrieves the full name of the author associated with the instantiated object. The method simply concatenates the first, middle and last names, using the join and filter methods to omit parts of the name that might be empty strings, such as with an author who does not use a middle name or initial. The method returns the author's full name as output.

The third method, update_name, changes the author's name based on user input. The method includes the same three input parameters as the class itself: first, middle and last. Also like the class, each parameter is assigned a default value, which is an empty string. In this way, an application can create an Author object or update the properties in the object by specifying the individual arguments, as in first='Zora'. After updating the author's name, the method runs the get_name method and returns the new full name.

For this example, the class is saved to a file named BookClasses.py, which can then be referenced from another Python file just like a module. The next script imports the Author class from BookClasses and then creates four Author objects.

from BookClasses import Author

auth1 = Author('Zora', 'Neale', 'Hurston')
auth2 = Author('Mark', '', 'Twain')
auth3 = Author(first='Virginia', last='Woolf')
auth4 = Author('Arthur', 'C.', 'Clarke')

auths = [auth1, auth2, auth3, auth4]
count = 1

for auth in auths:
  auth_name = auth.get_name()
  print(str(count) + '. ' + auth_name)
  count += 1

The first Author object definition calls the Author class and passes in three arguments for the author's name. The object is assigned to the auth1 variable. The variable can then be referenced later in the script to access the class's methods.

The other three Author object definitions work in a similar way. The only difference, other than author names, is that the auth3 object uses the parameter names when passing in the arguments. In this way, only those arguments need to be provided, and they can be specified in any order.

After the Author objects have been created, they're added to the auths list. Next, a for loop iterates through the list, running the get_name method on each Author object and then printing the author's full name. The for loop also increments the counter so that a new number is assigned to each author, giving us the following results.

1. Zora Neale Hurston
2. Mark Twain
3. Virginia Woolf
4. Arthur C. Clarke

The next Python script demonstrates how to use the update_name method in the Author class, once again importing the class from BookClasses.

from BookClasses import Author

auth = Author('Edgar', 'A.', 'Poe')

new_name = auth.update_name('Edgar', 'Allan', 'Poe')
print(new_name)

After importing the Author class, the script creates an Author object and assigns it to the auth variable, similar to how it was done in the previous script. The variable is then used to call the update_name method, passing in the updated author's name. The script assigns the method's output to the new_name variable and then prints the variable's value, giving the following results.

Updated name: Edgar Allan Poe

The ability to create classes and methods and then access those methods through instantiated objects is one of the most powerful capabilities in OOP languages. Languages such as C++, C#, Java and Python rely heavily on classes and methods to carry out the types of procedural logic inherent in today's applications. In C#, for example, all executed instructions are performed within the context of methods. In fact, the entry point for every C# application is the Main method.

Explore the basics of functional vs. object-oriented programming.

22 Feb 2023

All Rights Reserved, Copyright 1999 - 2024, TechTarget | Read our Privacy Statement