Objects can call methods, which are defined methods are defined in classes. Methods can modify all variables of an object.
A class method works on the class itself instead of on one object. It gets the
class as its first argument, cls, in the same way an instance method gets
the object as self.
Most of the time you do not need one. It is for the cases where the thing you are working on is the class, not an object made from it.
Inside the class you have to use the self keyword, which refers to the instance created from the class.
Because methods can be called from an object (instance), they are sometimes called instance methods.
python class methods
If you have a class Phone, you can create one or more new phone objects (instances). If you say define the class Phone you can create the object Nexus. In code that would look like this:
class Phone: |
In this example the class has a method addContact(). We call this method on the object, by typing object.method(). In this case, object.addContact().
The function will add a new contact to the list, but it doesn’t matter which function you define or what it does.
In the example above, we create an object Nexus. On this object we can call the methods call() and addContact(). Those methods are defined in the class, but change the objects variables.

The core idea is that an object can have one or more methods. If you call the method, it can change the objects properties.
nexus = Phone() |
Create class method
To make this method call work, the method called on the object addContact() needs to exist within the class Phone.
While we’re at it, also add a contact list to the class (all objects variables are defined inside the class).
class Phone: |
Do you see the self keyword in the code above, this refers to the current objects variables.
The class itself has the methods and variables:class Phone:
contacts = []
def call(self):
print('Calling')
def addContact(self, name):
self.contacts.append(name)
Every object you create has unique variables. If you create 3 objects, all of them have their own unique variables.
In the next article we’ll discuss the self keyword.
When it makes sense
- A factory method that builds and returns an object, so the constructor logic sits in one place.
- A method that changes class level variables, which are shared by every object of that class.
- A class method that does not need the object at all.
Add the decorator @classmethod above the method. Then call it on the
class, MyClass.build(), and not on an instance.
Compare the three:
- An instance method takes
selfand works on one object. - A class method takes
clsand works on the class. - A static method takes neither and is really just a function that happens to sit in the class.
cls means a subclass gets its own version automatically, which is why
factory methods are usually written as class methods.
Reading helps, writing fixes it. PyChallenge has exercises on this and you can try them right now.
