When calling a method in a class why do I use self.method() instead of method(variable)


#1

Not fully understanding why some things about classes, such as why I have to set self.variable = variable (don’t understand why it’s not just automatically being set when im setting all the objects in the init method). Right now the biggest thing I confuse myself on is I’ve always called functions to use by doing:

method(variable)

But now when calling a method from a class it’s:

self.method()

I’m not fully understanding why the prior doesn’t work in this scenario, maybe I’m looking over something really basic here, hoping someone can enlighten me.


#2

There is not such thing as method(variable). It is a function, as in, function(argument).

A method is a member function of a class instance, the instance being designated by self, the current owner.

class Foo(object):
    def __init__(self, name, id):
        self.name = name
        self.id = id
    def __repr__(self):
        return "Name: {}\nID: {}".format(self.name, self.id)

foo = Foo("foo", 42)
print (foo)
# Name: foo
# ID: 42

#3

Is there a difference between a method and a function, aside from a method being a function inside of a class?


#4

No, they are both functions. A method has a context (self, the instance), whereas a function does not. A function can operate in any environment.

Consider the built-in function, len(). It can be used on all sorts of objects, strings, lists, dictionaries, tuples and sets. It does not belong to any one class.

Now consider the string method, str.lower(). The dot tells us that .lower() is a method of the str class. We cannot use the method on any other type of objects because they are not instances of the str class.


#5

if inside your class you had a method called my_name looking something like this:

def my_name(self, name):
  print "my name is %s" % (name)

It still doesn’t fully click why you couldn’t do my_name(foo) instead of foo.my_name() but I’ll probably understand more with experience.

I think I might understand to some extent though; foo.my_name() works because you’re calling it from a class, whereas my_name(foo) would only work if the function was written outside of a class.


#6

my_name does not exist in global scope, but in a class. We can only access the method one of two ways.

  1. On an instance.
  2. On the class itself.

From the Python 2.7 documentation…

class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'

print (MyClass.f(0))    # hello world

Note that we passed in a dummy argument to satisfy the self parameter.