_F_unctions defined under a class are also called methods. Most of the methods are accessed through an instance of the class.
There are three types of methods:
- Instance methods
- Static methods
- Class methods
Both Static methods and Class methods can be called using the @staticmethod and @classmethod syntactic sugar respectively.
Instance methods#
_I_nstance methods are also called Bound methods since the instance is bound to the class via self. Read a simple explanation on self here.
Almost all methods are Instance methods since they are accessed through instances.
For example:
1class MyClass(object):
2
3def set_val(self, val): self.value = val
4
5def get_val(self): print(self.value) return self.value
6
7a = MyClass() b = MyClass()
8
9a.set_val(10) b.set_val(100)
10
11a.get_val() b.get_val()The above code snippet shows manipulating the two methods set_val() and get_val() . These are done through the instances a and b. Hence these methods are called Instance methods.
NOTE: Instance methods have self as their first argument. self is the instance itself.
All methods defined under a class are usually called via the instance instantiated from the class. But there are methods which can work without instantiating an instance.
Class methods and Static methods don't require an instance, and hence don't need self as their first argument.
Static methods#
Static methods are functions/methods which doesn't need a binding to a class or an instance.
- Static methods, as well as Class methods, don't require an instance to be called.
- Static methods doesn't need
selforclsas the first argument since it's not bound to an instance or class. - Static methods are normal functions, but within a class.
- Static methods are defined with the keyword
@staticmethodabove the function/method. - Static methods are usually used to work on Class Attributes.
============================= A note on class attributes
Attributes set explicitly under a class (not under a function) are called Class Attributes.
For example:
1class MyClass(object): value = 10
2
3def my_func(self): passIn the code snippet above, value = 10 is an attribute defined under the class MyClass() and not under any functions/methods. Hence, it's called a Class attribute. =============================
Let's check out an example on static methods and class attributes:
1class MyClass(object): # A class attribute count = 0
2
3def __init__(self, name): print("An instance is created!") self.name = name MyClass.count += 1
4
5# Our class method @staticmethod def status(): print("The total number of instances are ", MyClass.count)
6
7print(MyClass.count)
8
9my_func_1 = MyClass("MyClass 1") my_func_2 = MyClass("MyClass 2") my_func_3 = MyClass("MyClass 3")
10
11MyClass.status() print(MyClass.count)This prints the following:
1# python statismethod.py
2
30 An instance is created! An instance is created! An instance is created!
4
5The total number of instances are 3 3How does the code work?
- The example above has a class
MyClass()with a class attributecount = 0. - An init magic method accepts a
namevariable. - The init method also increments the count in the
countcounter at each instantiation. - We define a staticmethod
status()which just prints the number of the instances being created. The work done in this method is not necessarily associated with the class or any functions, hence its defined as a staticmethod. - We print the initial value of the counter
countvia the class, asMyClass.count. This will print0since the counter is called before any instances are created. - We create three instances from the class
MyClass - We can check the number of instances created through the
status()method and thecountcounter.
Another example:
1class Car(object):
2
3def sound(): print("vroom!")The code above shows a method which is common to all the Car instances, and is not limited to a specific instance of Car. Hence, this can be called as a staticmethod since it's not necessarily bound to a Class or Instance to be called.
1class Car(object):
2
3@staticmethod def sound(): print("vroom!")Class methods#
We can define functions/methods specific to classes. These are called Class methods.
The speciality of a class methods is that an instance is not required to access a class method. It can be called directly via the Class name.
Class methods are used when it's not necessary to instantiate a class to access a method.
NOTE: A method can be set as a Class method using the decorator @classmethod.
Example:
1class MyClass(object): value = 10
2
3@classmethod def my_func(cls): print("Hello")NOTE: Class methods have cls as their first argument, instead of self.
Example:
1class MyClass(object): count = 0
2
3def __init__(self, val): self.val = val MyClass.count += 1
4
5def set_val(self, newval): self.val = newval
6
7def get_val(self): return self.val
8
9@classmethod def get_count(cls): return cls.count
10
11object_1 = MyClass(10) print("\\nValue of object : %s" % object_1.get_val()) print(MyClass.get_count())
12
13object_2 = MyClass(20) print("\\nValue of object : %s" % object_2.get_val()) print(MyClass.get_count())
14
15object_3 = MyClass(40) print("\\nValue of object : %s" % object_3.get_val()) print(MyClass.get_count())Here, we use a get_count() function to get the number of times the counter was incremented. The counter is incremented each time an instance is created.
Since the counter is not really tied with the instance but only counts the number of instance, we set it as a classmethod, and calls it each time using MyClass.get_count()when an instance is created. The output looks as following:
1# python classmethod.py
2
3Value of object : 10 1
4
5Value of object : 20 2
6
7Value of object : 40 3
Courtsey: This was written as part of studying class and static methods. Several articles/videos have helped including but not limited to the following:
