Python Programming – Method

In this Page, We are Providing Python Programming – Method. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Method


A method is a function that belongs to an object. In Python, the term “method” is not unique to class instance, other object types can have methods as well. For example, list objects have methods, namely, append, insert, remove, sort, and so on.

Usually in a class, the method is defined inside its body. If called as an attribute of an instance of that class, the method will get the instance object as its first argument (which is usually called self). Self is merely a conventional name for the first argument of a method. For example, a method defined as meth (self, a, b, c) should be called as x.meth (a, b, c) for an instance x of the class in which the definition occurs; the called method will think it is called as meth (x, a, b, c). The idea of self was borrowed from “Modula-3” programming language.

It is not necessary that the function definition is textually enclosed in the class definition; assigning a function object to a local variable in the class is also fine. For example:

>>> def f 1 ( self , x , y ) :
. . .            return min ( x , x+y )
. . . 
>>> class test_class :
. . .        aa=f1
. . .        def bb ( self ) : 
. . .              return ' hello world '
. . .       cc=bb
. . . 

Here aa, bb and cc are all attributes of class test_class that refer to function objects, and consequently, they are all methods of instances of class test_class; cc being exactly equivalent to bb. Note that this practice usually confuses the reader of the program.

Usually, Python use methods for some functionality (e.g. list. index ()), but functions for other (e.g. len (list)). The major reason is history; functions were used for those operations that were generic for a group of types and which were intended to work even for objects that did not have methods at all (e.g. tuples). In fact, implementing len ( ), max ( ), min ( ) etc.

as built-in functions has actually less code than implementing them as methods for each type. One can quibble about individual cases, but it is part of Python, and it is too late to make such fundamental changes now. The functions have to remain to avoid massive code breakage.