Python 如何创建静态类数据和静态类方法
Python包含静态类数据和静态类方法的概念。
静态类数据
在这里,为静态类数据定义一个类属性。如果要给属性赋新值,则在赋值时明确使用类名-
class Demo:
count = 0
def __init__(self):
Demo.count = Demo.count + 1
def getcount(self):
return Demo.count
我们还可以返回以下内容而不是返回Demo.count −。
return self.count
在Demo的方法中,类似self.count = 42的赋值操作会在self的字典中创建一个新的和count无关的实例。无论在方法内部还是外部,重新绑定类静态数据名称都必须明确指定类-
Demo.count = 314
静态类方法
让我们看一下静态方法是如何工作的。静态方法绑定在类上而不是类的对象上。静态方法用于创建实用函数。
静态方法无法访问或修改类状态。静态方法不知道类的状态。这些方法用于通过传递参数来执行一些实用任务。
记住,@staticmethod装饰器用于创建静态方法,如下所示:
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