如何在Python中创建静态类数据和静态类方法?
Python包括静态类数据和静态类方法的概念。
静态类数据
在这里,为静态类数据定义一个类属性。如果要为属性分配一个新值,显式使用类名进行赋值 –
class Demo:
count = 0
def __init__(self):
Demo.count = Demo.count + 1
def getcount(self):
return Demo.count
我们还可以返回以下内容,而不是return Demo.count –
return self.count
在Demo的方法中,像self.count = 42这样的赋值会在self自己的字典中创建一个新的和不相关的实例。类静态数据名称的重新绑定必须始终指定类,无论在方法内外都是如此。
Demo.count = 314
静态类方法
让我们看看静态方法如何工作。静态方法绑定到类而不是类的对象。静态方法用于创建实用函数。
静态方法不能访问或修改类状态。静态方法不知道类状态。这些方法用于通过采用一些参数执行某些实用任务。
记住,@staticmethod装饰器用于创建静态方法,如下所示 –
class Demo:
@staticmethod
def static(arg1, arg2, arg3):
#没有'self'参数!
...
示例
让我们看一个完整的例子 –
从 datetime 导入 date
类 Student:
def __init__(self, name, age):
self.name = name
self.age = age
# 一个类方法
@classmethod
def birthYear(cls, name, year):
return cls(name, date.today().year - year)
# 一个静态方法
# 如果 Student 的年龄超过 18 岁或不到 18 岁
@staticmethod
def checkAdult(age):
return age > 18
# 创建 4 个对象
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)
# 显示结果
print(Student.checkAdult(22))
print(Student.checkAdult(20))
输出
Student1 Age = 20
Student2 Age = 21
Student3 Age = 22
Student4 Age = 19
True
True
极客教程