Home  >  Article  >  Backend Development  >  How to create static class data and static class methods in Python?

How to create static class data and static class methods in Python?

WBOY
WBOYforward
2023-09-07 22:13:02699browse

How to create static class data and static class methods in Python?

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

Static class data

Here, define a class attribute for static class data. If you want to assign a new value to a property, explicitly use the class name -

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

Instead of returning Demo.count -

we can also return the following
return self.count

In Demo's method, an assignment like self.count = 42 creates a new, unrelated instance named count in self's own dictionary. Rebinding of class static data names must always specify the class, whether inside a method or not -

Demo.count = 314

Static class method

Let's see how static methods work. Static methods are bound to a class rather than an object of the class. The status method is used to create utility functions.

Static methods cannot access or modify class state. Static methods have no knowledge of class state. These methods are used to perform some practical tasks by getting some parameters.

Remember, the @staticmethod decorator is used to create static methods as shown below -

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

Example

Let’s 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

The above is the detailed content of How to create static class data and static class methods in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete