Difference Between Methods and Functions, in Python Compared to C++

Difference between methods and functions, in Python compared to C++

Needs Attention: This answer seems to be outdated. Check this

A function is a callable object in Python, i.e. can be called using the call operator (though other objects can emulate a function by implementing __call__). For example:

>>> def a(): pass
>>> a
<function a at 0x107063aa0>
>>> type(a)
<type 'function'>

A method is a special class of function, one that can be bound or unbound.

>>> class A:
... def a(self): pass
>>> A.a
<unbound method A.a>
>>> type(A.a)
<type 'instancemethod'>

>>> A().a
<bound method A.a of <__main__.A instance at 0x107070d88>>
>>> type(A().a)
<type 'instancemethod'>

Of course, an unbound method cannot be called (at least not directly without passing an instance as an argument):

>>> A.a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method a() must be called with A instance as first argument (got nothing instead)

In Python, in most cases, you won't notice the difference between a bound method, a function, or a callable object (i.e. an object that implements __call__), or a class constructor. They all look the same, they just have different naming conventions. Under the hood, the objects may look vastly different though.

This means that a bound method can be used as a function, this is one of the many small things that makes Python so powerful

>>> b = A().a
>>> b()

It also means that even though there is a fundamental difference between len(...) and str(...) (the latter is a type constructor), you won't notice the difference until you dig a little deeper:

>>> len
<built-in function len>
>>> str
<type 'str'>

What is the difference between functions in Python and functions in C++?

In C/C++, the main() function is the program entry point.

In python their is no such main() functions which are the program entry point and don't automatically run unless they are called. But the behaviour cam be implemented.

def main():
# Your code

if __name__ == '__main__':
main()

Then main() will run if script is executed (not imported)

Also python does not require main() functions like C++, all code in the script outside any function (which is not called) is executed

What's the difference between a method and a function?

A function is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.

A method is a piece of code that is called by a name that is associated with an object. In most respects it is identical to a function except for two key differences:

  1. A method is implicitly passed the object on which it was called.
  2. A method is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data).

(this is a simplified explanation, ignoring issues of scope etc.)

Python method vs function

Yes. To be clear, methods are functions, they are simply attached to the class, and when that function is called from an instance it gets that instance passed implicitly as the first argument automagically*. It doesn't actually matter where that function is defined. Consider:

class FooBar:
def __init__(self, n):
self.n = n
def foo(self):
return '|'.join(self.n*['foo'])

fb = FooBar(2)

print(fb.foo())

def bar(self):
return '*'.join(self.n*['bar'])

print(bar(fb))

FooBar.bar = bar

print(fb.bar())

*I highly recommend reading the descriptor HOWTO. Spoiler alert, Functions are descriptors. This is how Python magically passes instances to methods (that is, all function objects are descriptors who's __get__ method passes the instance as the first argument to the function itself when accessed by an instance on a class!. The HOWTO shows Python implementations of all of these things, including how you could implement property in pure Python!

Differentiating between built-in functions vs built-in methods in Python

A method is a function which is applicable to a certain class, while a function can be used in any valid class. Like the sort method for the list class sorts the list. Methods of mutable types mostly change the item, so list.sort would set the value of list to the sorted value of list and return None. But methods of immutable types like strings will return a new instance of the thing as seen below.

question = "How is this?"
question.replace("How", "What") # Returns "What is this", but does not change question.
print(question) # Prints "How is this?"
print(question.replace("How", "What")) # Prints "What is this"

Built in functions like sorted do not change the item, they return a new version, or instance, of it.

list1 = [4,3,6,2]
sorted(list1) # Returns [2,3,4,6], but does not modify list.
print(list1) # Prints [4,3,6,2]
list1.sort() # Returns None, but changes list.
print(list1) # Prints [2,3,4,6]

When you use a method, you put a period after the variable to show that it can only be used for that specific class. Why some functions require arguments while some methods don't - like sorted(list) requires list, but list.sort() doesn't require arguments, is that when you use a method on a class, Python by default passes in a parameter called self, which is the actual variable, list in this case. If you have worked with JavaScript, self is something like the this keyword in JS.

So when you enter list.sort(), Python is actually running the function sort inside the list class passing it a parameter of self.

objective c difference between functions and methods

First, I'm a beginner in Objective-C, but I can say what I know.

Functions are code blocks that are unrelated to an object / class, just inherited from c, and you call them in the way:

// declaration
int fooFunction() {
return 0;
}

// call
int a;
a = fooFunction();

While methods are attached to class / instance (object) and you have to tell the class / object to perform them:

// declaration
- (int)fooMethod {
return 0;
}

// call
int a;
a = [someObjectOfThisClass fooMethod];

Classes vs. Functions

Create a function. Functions do specific things, classes are specific things.

Classes often have methods, which are functions that are associated with a particular class, and do things associated with the thing that the class is - but if all you want is to do something, a function is all you need.

Essentially, a class is a way of grouping functions (as methods) and data (as properties) into a logical unit revolving around a certain kind of thing. If you don't need that grouping, there's no need to make a class.

Difference between this C++ function and Python function

You're using floating point division in the Python code:

b/=2

You want integer division:

b //= 2

difference between method and function

There is no difference for many built-in functions. The global functions like len, iter, str are calls to object methods __len__, __iter__, __str__ etc.

See Basic customization and Emulating container types in Python reference:

object.__len__(self)

Called to implement the built-in function len(). Should return the length of the object, an integer >= 0. ...

Advantage of such soluttion is that an object can override these special functions just by overriding corresponding "double-underscore" methods, e.g __len__.

Although append does not have a built-in, since it is a less universal operation than len, str etc.



Related Topics



Leave a reply



Submit