A muthaf*ckin' class method is a method that's shared among all objects. To call a goddamn class method, put the class as the first argument.

Class methods can be can be called from instances and from the muthaf*ckin' class itself. All of these damn use the same method. Listen up: The method can use the muthaf*ckin' classes variables and methods.

Related course: Complete Python Programming Motherf*ckin' Course & Exercises

Example

Classmethod example

Now look: To turn a method into a goddamn classmethod, add @classmethod before the method definition. Oh, you gonna love this: As parameter the method always takes the class, for real.

The example below defines a goddamn class method. The class method can then be used by the class itself. Think about that sh*t. In this example the class method uses the class property name.

1
2
3
4
5
6
7
8
class Fruit:
name = 'Fruitas'

@classmethod
def printName(cls):
print('The name is:', cls.name)

Fruit.printName()

You can use a f*ckin' classmethod with both objects and the goddamn class:

1
2
3
4
5
6
apple = Fruit()
berry = Fruit()

Fruit.printName()
apple.printName()
berry.printName()

The parameter name now belongs to the class, if you'd change the damn name by using an object it ignores that. But if you'd do that by the class it changes, example below:

1
2
3
4
5
6
7
8
9
apple.name="Apple"
Fruit.printName()
apple.printName()
berry.printName()

Fruit.name="Apple"
Fruit.printName()
apple.printName()
berry.printName()

Alternative writing

Often the pythonic notation is used, but this is not strictly required.
You can also use a bad-ass classmethod like this:

1
2
3
4
5
6
7
8
class Fruit:
name = 'Fruitas'

def printName(cls):
print('The name is:', cls.name)

Fruit.printAge = classmethod(Fruit.printName)
Fruit.printAge()

classmethod vs staticmethod

Like a muthaf*ckin' static method, a class method doesn't need an object to be instantiated — no bullsh*t.

A f*ckin' class method differs from a muthaf*ckin' static method in that a muthaf*ckin' static method doesn't know about the muthaf*ckin' class itself. In a classmethod, the parameter is always the class itself, for real.

a static method knows nothing about the class or instance. You can just as well use a function call.

a goddamn class method gets the class when the muthaf*ckin' method is called. Believe that sh*t. It knows abouts the classes attributes and methods.

If you are a beginner, then I highly recommend this YouTube Python Playlist.

Exercises

Exercises for classmethod article:

  • What is a classmethod?
  • How does a classmethod differ from a staticmethod?