user10443608
user10443608

Reputation:

is it necessary to distinguish method and function in python3?

There are a lot of methods and functions in Python.

here is a piece of code

a = list('hello,world')
len(a)

the doc says len() is a

builtin_function_or_method

i know the difference between a method and a function, a method is in the context of object, a Functions isn't.

the question is, is it necessary to distinguish method and function in a blog?

for instance, I am writing a tutorial, i could say

expression_1: len(a) function gives the number of elements in list a

or

expression_2: len(a) method gives the number of elements in list a

is it necessary to distinguish the terms in such scenarios?

Upvotes: 1

Views: 195

Answers (3)

prosti
prosti

Reputation: 46331

Python built-in type() can provide you good debugging information. For example.

class C:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def m1(self, x):
        print("Excellent {}".format(x))

    @classmethod
    def m2(cls, x):
        print("Excellent cls {}".format(x))

    @staticmethod
    def m3(x):
        print("Excellent static {}".format(x))    

ci=C("John", 36)
L=dir(C) # c is a class
for i in L:
    print("C::", i, type(eval('ci.'+i)))

The last three lines of output:

...
C:: m1 <class 'method'>
C:: m2 <class 'method'>
C:: m3 <class 'function'>

Shows the distinction between the method and a function. When something is static in nature like the m3 then it is a function, else it is a method.

When something is a function you will clearly know.

def foo():
    pass

type(foo)  # function

Upvotes: 0

Kyle
Kyle

Reputation: 1170

To answer the updated question about documenting code: yes, that distinction is important. It is correct to say that len is a function, and incorrect to say that it is a method.


Here is a quick StackOverflow explanation of the difference between a function and a method.

Specific to Python, there is not much of a difference in usefulness between the two. There are a few subtle differences between the usage of functions and methods. Functions are defined by themselves, while methods are defined inside the definition of the class they belong to. For example:

def my_function(my_custom_object):
    """This is a function. See how it's defined separately from any of the objects
    it operates on."""
    return my_custom_object.custom_method()


class MyCustomClass:
    def __init__(self, some_param, other_param):
        self.first = some_param
        self.second = other_param

    def custom_method(self):
        do_stuff(self.first)
        return do_other_things(self.second)


my_obj = MyCustomClass('foo', 'bar')
print(my_obj.custom_method())
print(my_function(my_obj))

In the definition of a method, the first argument is usually self. This is the position where Python places the object the method belongs to; this way, the method can use other attributes and methods belonging to the object. Note the difference between when you call the method custom_method and when you call the function my_function. When you call a method, the object is implicitly passed as the first parameter (self).

In Python you can use the class's member method and apply it to an object of that type (or any other type for that matter) like so:

MyCustomClass.custom_method(my_obj)

Semantically, methods are generally used when the process being performed "belongs" to the object in a way that a function's process does not. For example, dog.bark() is probably better than bark(dog).

Upvotes: 0

ShadowRanger
ShadowRanger

Reputation: 155363

As a matter of terminology, methods are attached to class instances (or classes themselves, for classmethods and staticmethods), functions aren't.

In practice, in Python 3, the distinction is much weaker than it used to be. Originally, in Python 2, "methodness" was more important; defining a function within a class made it an unbound method if referenced from the class, and a bound method if referenced on the instances.

In Python 3, the concept of unbound methods is gone; when referenced from the class itself, you get a plain function, not a method (bound or unbound); you only get a bound method when you reference the method from an instance of the class.

Essentially, there are really two categories of things now:

  1. Functions which can't be bound as methods (because they don't implement the descriptor protocol to produce bound methods; applies solely to built-in functions in CPython)
  2. Functions which can be bound as methods (includes all functions defined in Python itself)

Everything in category 2 is a function which can act as a method if attached to a class, then referenced from an instance of said class. The nomenclature describes the intent, but as a matter of implementation, there is very little difference left.

Note that even in Python 2, the two category approach was the same, it's just that the descriptor protocol for functions was invoked even when loaded from the class itself (to bypass it and get the raw function without creating an unbound method, you had to do ClassName.__dict__['methodname']). So it's always been the case that methods are just the result of binding functions as a matter of implementation.

Upvotes: 3

Related Questions