Object Oriented

Method

Python

 

Defining Mehtod

Python 2.7
class Person:
  
  def greet():
    print("Hi!")

Methods are actions performed on objects.

Methods are like functions, They may get some input and may return a value.

If a method finishes without returning anything, the return value will be None.

 

Method Parameters

Python 2.7
class Person:
  
  # ...

  def getName(self):
    return self.name

  def setName(self, name):
    self.name = name

  def sleep(self, fromTime, duration):
    output = self.getName() + " slept from " + \
        str(fromTime) + " for " + str(duration) + " hours."
    print(output)

Parameters are inputs to methods.

Parameters are separated by comma (,).

Parameters are passed by assignment (reference values).

 

Invoking Methods

Python 2.7
person1 = Person()

person1.setName("Sam")
name = person1.getName() # Sam
person1.sleep(10, 7) # Sam slept from 10 for 7 hours.

Methods of an object can be accessed like any properties on it.

Notice although in method definitions the first parameter is self, when a method is called we are not passing anything for that.

Arguments can also be passed to a method with key-value syntax (Keyword Arguments). You can learn more about this in Function Topic.

 

Invoking Methods from inside Class

Python 2.7
class Person:
  
  # ...
  
  def birthday(self):
    self.setAge(self.getAge() + 1)

Methods can be accessed from inside a class explicitly by calling it on self (first parameter).