python staticmethod, classmethod and instancemethod¶
Python Static Methods¶
In python classes we define static methods using the decorator @staticmethod . Let's check out the python static method syntax below.
class Circle(object):
@staticmethod
def area(radius):
return (22/7.0)*radius*radius
area = Circle.area(10)
print(area)
# Output: 314.285714286
- We can define the static method without using decorator also but it will not be available on class instances.
- We can use static methods when the code of the method only belongs to the class and it do not require the self or the object itself.
- staticmethod is nothing more than a function defined inside a class.
- It is callable without instantiating the class first. Itβs definition is immutable via inheritance.
Python Class Methods¶
In python classes we define class methods using the decorator @classmethod. Let's check out the python class method syntax below.
class Date(object):
def __init__(self, day=0, month=0, year=0):
self.day = day
self.month = month
self.year = year
@classmethod
def from_string(cls, date_as_string):
day, month, year = map(int, date_as_string.split('-'))
date = cls(day, month, year)
return date
def __str__(self):
return 'Date({}, {}, {})'.format(self.day, self.month, self.year)
d = Date.from_string('01-12-2019')
print(d)
# Output: Date(1, 12, 2019)
- Python class methods are not specific to a particular instance but they involved with the class.
- Python class methods can be overridden by its child classes.
- classmethod decorator also improves the code readability.
Python Instance Methods¶
- Unike the static and class methods, python instance methods does not require any decorator. Let's check out the python instance method syntax below.
class User(object):
def __init__(self, user_id, first_name, last_name):
self.user_id = user_id
self.first_name = first_name
self.last_name = last_name
def get_full_name(self):
return '{} {}'.format(self.first_name, self.last_name)
u1 = User(1, 'Anji', 'B')
print(u1.get_full_name())
# Output: Anji B
u2 = User(2, 'Shiva', 'D')
print(u2.get_full_name())
# Output: Shiva D