Difference between class and instance methods

I was reading PEP 8 (style guide), and I noticed that it suggested to use self as the first argument in an instance method, but cls as the first argument in a class method.

I've used and written a few classes, but I've never encountered a class method (well, a method which passes cls as a parameter). What are some examples?


Solution 1:

Instance methods

When creating an instance method, the first parameter is always self. You can name it anything you want, but the meaning will always be the same, and you should use self since it's the naming convention. self is (usually) passed hiddenly when calling an instance method; it represents the instance calling the method.

Here's an example of a class called Inst that has an instance method called introduce():

class Inst:

    def __init__(self, name):
        self.name = name

    def introduce(self):
        print("Hello, I am %s, and my name is " %(self, self.name))

Now to call this method, we first need to create an instance of our class. Once we have an instance, we can call introduce() on it, and the instance will automatically be passed as self:

myinst = Inst("Test Instance")
otherinst = Inst("An other instance")
myinst.introduce()
# outputs: Hello, I am <Inst object at x>, and my name is Test Instance
otherinst.introduce()
# outputs: Hello, I am <Inst object at y>, and my name is An other instance

As you see, we're not passing the parameter self. It gets hiddenly passed with the period operator. We're calling Inst class's instance method introduce, with the parameter of myinst or otherinst. This means that we can call Inst.introduce(myinst) and get the exact same result.


Class methods

The idea of a class method is very similar to an instance method, only difference being that instead of passing the instance hiddenly as a first parameter, we're now passing the class itself as a first parameter.

class Cls:

    @classmethod
    def introduce(cls):
        print("Hello, I am %s!" %cls)

Since we're passing only a class to the method, no instance is involved.

This means that we don't need an instance at all, and we call the class method as if it was a static function:

 Cls.introduce() # same as Cls.introduce(Cls)
 # outputs: Hello, I am <class 'Cls'>

Notice that again Cls is passed hiddenly, so we could also say Cls.introduce(Inst) and get output "Hello, I am <class 'Inst'>.

This is particularly useful when we're inheriting a class from Cls:

class SubCls(Cls):
    pass

SubCls.introduce()
# outputs: Hello, I am <class 'SubCls'>

Solution 2:

An instance method, simply put, is a function defined inside of a class. It varies with the different instances of the class. Example:

class Dog:
    def __init__(self, sound):
        self.sound = sound
    def bark(self):
        return f"The dog makes the sound: {self.sound}"

Whereas a class method is a method which, unlike the bark() method, is applied to all instances of the class.