How to use Python’s @classmethod and @staticmethod

The @classmethod Decorator

class Student(object):      
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
scott = Student('Scott', 'Robinson')
class Student(object):          @classmethod     
def from_string(cls, name_str):
first_name, last_name = map(str, name_str.split(' '))
student = cls(first_name, last_name)
return student
scott = Student.from_string('Scott Robinson')
class Student(object):          @classmethod     
def from_string(cls, name_str):
first_name, last_name = map(str, name_str.split(' '))
student = cls(first_name, last_name)
return student
@classmethod
def from_json(cls, json_obj):
# parse json...
return student
@classmethod
def from_pickle(cls, pickle_file):
# load pickle file...
return student

The @staticmethod Decorator

class Student(object):

@staticmethod
def is_full_name(name_str):
names = name_str.split(' ')
return len(names) > 1

Student.is_full_name('Scott Robinson') # True
Student.is_full_name('Scott') # False

@classmethod vs @staticmethod

A Longer Example

class ClassGrades:      
def __init__(self, grades):
self.grades = grades
@classmethod
def from_csv(cls, grade_csv_str):
grades = map(int, grade_csv_str.split(', '))
cls.validate(grades)
return cls(grades)
@staticmethod
def validate(grades):
for g in grades:
if g < 0 or g > 100:
raise Exception()
try:
# Try out some valid grades
class_grades_valid = ClassGrades.from_csv('92, 83, 82, 93, 79')
print 'Got grades:', class_grades_valid.grades

# Should fail with invalid grades
class_grades_invalid = ClassGrades.from_csv('91, -19, 98, 104, 72, 65, 100')
print class_grades_invalid.grades
except:
print 'Invalid!'

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store