class Demo: @staticmethod def static(arg1, arg2, arg3): # No 'self' parameter! ...
例
让我们看一个完整的例子 -
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))
输出
Student1 Age = 20
Student2 Age = 21
Student3 Age = 22
Student4 Age = 19
True
True