40classmethod vs 40staticmethod vs 22plain 22 methods

Solutions on MaxInterview for 40classmethod vs 40staticmethod vs 22plain 22 methods by the best coders in the world

showing results for - " 40classmethod vs 40staticmethod vs 22plain 22 methods"
Leticia
05 Aug 2016
1# @classmethod vs @staticmethod vs "plain" methods
2# What's the difference?
3
4class MyClass:
5    def method(self):
6        """
7        Instance methods need a class instance and
8        can access the instance through `self`.
9        """
10        return 'instance method called', self
11
12    @classmethod
13    def classmethod(cls):
14        """
15        Class methods don't need a class instance.
16        They can't access the instance (self) but
17        they have access to the class itself via `cls`.
18        """
19        return 'class method called', cls
20
21    @staticmethod
22    def staticmethod():
23        """
24        Static methods don't have access to `cls` or `self`.
25        They work like regular functions but belong to
26        the class's namespace.
27        """
28        return 'static method called'
29
30# All methods types can be
31# called on a class instance:
32>>> obj = MyClass()
33>>> obj.method()
34('instance method called', <MyClass instance at 0x1019381b8>)
35>>> obj.classmethod()
36('class method called', <class MyClass at 0x101a2f4c8>)
37>>> obj.staticmethod()
38'static method called'
39
40# Calling instance methods fails
41# if we only have the class object:
42>>> MyClass.classmethod()
43('class method called', <class MyClass at 0x101a2f4c8>)
44>>> MyClass.staticmethod()
45'static method called'
46>>> MyClass.method()
47TypeError: 
48    "unbound method method() must be called with MyClass "
49    "instance as first argument (got nothing instead)"