Methods (OOP) | Brilliant Math & Science Wiki (2024)

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.

sizeC sizeB sizeD sizeA

 1 2 3 4 5 6 7 8 9101112131415161718192021
class IceCream(object): def __init__(self, flavor, numScoops, costPerScoop, remaining_icecream): self.flavor = flavor self.numScoops = numScoops self.costPerScoop = costPerScoop self.remaining_icecream = remaining_icecream def scoop(self): #scoops icecream and decreases the number of scoops left self.remaining_icecream -= self.numScoops return self.remaining_icecream def total_cost(self): #vanilla ice cream is sold at a discount of half off! if self.flavor == "vanilla": total_cost = self.numScoops * .5*self.costPerScoop else: total_cost = self.numScoops * self.costPerScoop return total_cost

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.

1234567
def sizeA(self): if self.numScoops in range(1,3): print "small" elif self.numScoops in range(4,5): print "medium" else: print "large"
1234567
def sizeB(self): if self.numScoops in range(1,4): print "small" elif self.numScoops in range(4,6): print "medium" else: print "large"
1234567
def sizeD(self): if scoops in range(1,4): print "small" elif scoops in range(4,6): print "medium" else: print "large"

(ignore the fact that these functions may return None along with the size printed)

Contents

  • Methods
  • Interface Methods
  • Constructor
  • Implementation Methods
  • See Also

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.

1234567
myList = [1,2,3,4]myList.append(5)print myList#prints out [1,2,3,4,5]

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 91011121314151617181920
class Square(object): def __init__(self, sideLength): self.sideLength = sideLength # Getter: def getSideLength(self): return self.sideLength # Setter: def setSideLength(self,sideLength): self.sideLength = sideLengthsquare = Square(10.0)print square.getSideLength() # prints 10.0 to the screensquare.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 910111213141516171819
class Square(object): # Constructor: def __init__(self): self.sideLength = 5.0 def getSideLength(self): return self.sideLength def setSideLength(self,sideLength): self.sideLength = sideLengthsquare = Square() # invokes the constructor methodprint square.getSideLength() # prints 5.0 to the screensquare.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 9101112131415161718192021
class 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:

1234
def outputAreaTimesN(self, n): return (self.getSideLength() * self.getSideLength()) * nprint 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

  • Object-Oriented Programming

  • Classes

Basic Programming Pages

  • Subroutines

  • For Loops

  • While Loops

  • List Comprehension

Methods (OOP) | Brilliant Math & Science Wiki (2024)
Top Articles
Discover thousands of collaborative articles on 2500+ skills
10 Best Agencies in India for Unparalleled Business Growth
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Tuan Roob DDS

Last Updated:

Views: 5605

Rating: 4.1 / 5 (62 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Tuan Roob DDS

Birthday: 1999-11-20

Address: Suite 592 642 Pfannerstill Island, South Keila, LA 74970-3076

Phone: +9617721773649

Job: Marketing Producer

Hobby: Skydiving, Flag Football, Knitting, Running, Lego building, Hunting, Juggling

Introduction: My name is Tuan Roob DDS, I am a friendly, good, energetic, faithful, fantastic, gentle, enchanting person who loves writing and wants to share my knowledge and understanding with you.