Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a "method" in Python?

Tags:

python

methods

Can anyone, please, explain to me in very simple terms what a "method" is in Python?

The thing is in many Python tutorials for beginners this word is used in such way as if the beginner already knew what a method is in the context of Python. While I am of course familiar with the general meaning of this word, I have no clue what this term means in Python. So, please, explain to me what the "Pythonian" method is all about.

Some very simple example code would be very much appreciated as a picture is worth thousand words.

like image 364
brilliant Avatar asked Sep 24 '10 12:09

brilliant


People also ask

What is a method and function in Python?

Functions can be called only by its name, as it is defined independently. But methods can't be called by its name only, we need to invoke the class by a reference of that class in which it is defined, i.e. method is defined within a class and hence they are dependent on that class.

What is a method in function?

Function — a set of instructions that perform a task. Method — a set of instructions that are associated with an object.

What is a method class Python?

What is Class Method in Python. Class methods are methods that are called on the class itself, not on a specific object instance. Therefore, it belongs to a class level, and all class instances share a class method. A class method is bound to the class and not the object of the class. It can access only class variables ...

What is difference between a function and a method?

A function is a set of instructions or procedures to perform a specific task, and a method is a set of instructions that are associated with an object.


1 Answers

It's a function which is a member of a class:

class C:     def my_method(self):         print("I am a C")  c = C() c.my_method()  # Prints("I am a C") 

Simple as that!

(There are also some alternative kinds of method, allowing you to control the relationship between the class and the function. But I'm guessing from your question that you're not asking about that, but rather just the basics.)

like image 120
3 revs, 2 users 91% Avatar answered Sep 26 '22 22:09

3 revs, 2 users 91%