Regular Instance Methods vs Class Methods vs Static Methods
In this lesson you’ll dive deeper into the concepts behind instance, class and static methods. The differences are examined using a sample class.
00:00
So, I created this class, I call it MyClass
. It’s just a really simple example, and it’s got a couple of different method types on it. So, the first one is just called .method()
. The method is called .method()
, and it’s just a plain instance method. And you can see here, it takes one argument, the self
argument, which points to the object instance.
00:24
That means within .method()
, we can actually modify or read attributes on the object instance. And when you compare that to a class method—so, I just called this one .classmethod()
and then use the @classmethod
decorator to actually mark it as a class method—you can see here that the .classmethod()
only has access to this cls
(class) parameter, or cls
argument. It doesn’t have have a self
argument.
00:55
So, this means a class method it can only access the class itself—or the object representing the class, because well, everything is an object in Python. But the key difference is that when I create an instance of MyClass
and call .classmethod()
on it, it won’t be able to actually access the self
object, right?
01:15 So, it can only access attributes that actually exists on the class itself, and not on the instance. Now, with a static method, again, the approach is really similar.
01:27
You just define a regular method and then mark it with the @staticmethod
decorator. What you can see here is that it doesn’t take any arguments at all, so it has no access to the class or the object instance at all.
01:43 It’s completely separate from that, and it’s really just a way to namespace your methods. So now, you know, I know this is very theoretical at this point, and it’s going to become much more clear when we actually try and do some experimentation with this stuff—some hands-on work.
Bartosz Zaczyński RP Team on Sept. 24, 2020
An instance method accepts the self
reference, which points to a specific object that shares attributes with the corresponding class. You can use that reference to access object attributes and class attributes, whereas the cls
reference only lets you manipulate the class attributes.
It’s worth noting that self
and cls
are customary names, but you could very well use your own. Ultimately, it’s the decorators or their lack that determine what reference gets passed to a method.
So, to answer your question, you can use the first argument passed to an instance method (conventionally called self
) to manipulate an object state as well as the class state.
Become a Member to join the conversation.
Mariko on Sept. 24, 2020
Thanks for the tutorial! Maybe you covered this, but I’m not sure what you mean by modifying class state in an instance method. Can we somehow access
cls
in an instance method?