How do I create static class data and static class methods in Python?


Python includes the concept of static class data and static class methods.

The static class data

Here, define a class attribute for the static class data. Explicitly use the class name in the assignment, if you want to assign a new value to the attribute −

class Demo: count = 0 def __init__(self): Demo.count = Demo.count + 1 def getcount(self): return Demo.count

We can also return the following instead return Demo.count −

return self.count

Within a method of Demo, an assignment like self.count = 42 creates a new and unrelated instance named count in self’s own dict. Rebinding of a class-static data name must always specify the class whether inside a method or not −

Demo.count = 314

The static class methods

Let us see how static methods work. A static method is bound to the class and not the object of the class. The statis methods are used to create utility functions.

Static Method cannot access or modify the class state. The Static methods do not know about class state. These methods are used to do some utility tasks by taking some parameters.

Remember, the @staticmethod decorator is used to create a static method as show below −

class Demo: @staticmethod def static(arg1, arg2, arg3): # No 'self' parameter! ...

Example

Let us see a complete example −

from datetime import date class Student: def __init__(self, name, age): self.name = name self.age = age # A class method @classmethod def birthYear(cls, name, year): return cls(name, date.today().year - year) # A static method # If a Student is over 18 or not @staticmethod def checkAdult(age): return age > 18 # Creating 4 objects st1 = Student('Jacob', 20) st2 = Student('John', 21) st3 = Student.birthYear('Tom', 2000) st4 = Student.birthYear('Anthony', 2003) print("Student1 Age = ",st1.age) print("Student2 Age = ",st2.age) print("Student3 Age = ",st3.age) print("Student4 Age = ",st4.age) # Display the result print(Student.checkAdult(22)) print(Student.checkAdult(20))

Output

Student1 Age =  20
Student2 Age =  21
Student3 Age =  22
Student4 Age =  19
True
True

Updated on: 19-Sep-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements