Or is everything a method?
Since everything is an object, a
def whatever:
is just a method of that file.py, right?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Python has functions. As everything is an object functions are objects too.
So, to use your example:
When we use
defwe have created an object which is a function. We can, for example, look at an attribute of the object:In answer to your question –
whatever()is not a method offile.py. It is better to think of it as a function object bound to the namewhateverin the global namespace offile.py.Or to look at it another way, there’s nothing stopping us from binding the name
whateverto a different object altogether:There are other ways to create function objects. For example, lambdas:
A method is like attribute of an object that is a function. What makes it a method is that the methods get bound to the object. This causes the object to get passed to the function as the first argument which we normally call
self.Let’s define a class
SomeClasswith a methodsomemethodand an instancesomeobject:Let’s look at
somemethodas an attribute:We can see it’s a bound method on the object and an unbound method on the class. So now let’s call the method and see what happens:
As it’s a bound method the first argument received by
somemethodis the object and the second argument is the first argument in the method call. Let’s call the method on the class:Python complains because we’re trying to call the method without giving it an object of the appropriate type. So we can fix this by passing the object “by hand”:
You might use method calls of this type – calling a method on a class – when you want to call a specific method from a superclass.
(It is possible to take a function and bind it to class to make it a method, but this is not something that you’d normally ever need to do.)