property() 是 Python 中的内置函数,为实例属性提供接口。它封装实例属性并提供属性,与Java和C#相同。property() 方法将 get、set 和 delete 方法作为参数,并返回属性类的对象。
为了更好地理解,只需通过以下示例。
@property 装饰器的示例
class ThisIsMyClass:
def __init__(self, grade=None):
self.grade = grade
@property
def student_grade(self):
return self.grade
@student_grade.setter
def student_grade(self, grade):
self.grade = grade
@student_grade.deleter
def student_grade(self):
print("This is a delete method")
self.grade = 0
property_obj = ThisIsMyClass(80)
print(property_obj.student_grade)
property_obj.student_grade = 70
print(property_obj.student_grade)
del property_obj.student_grade
print(property_obj.student_grade)
输出:
80
70
This is a delete method
0
没有 @property 装饰器的示例
class ThisIsMyClass:
def __init__(self, grade=None):
self.grade = grade
def get_student_grade(self):
return self.grade
def set_student_grade(self, grade):
self.grade = grade
def delete_student_grade(self):
print("This is a delete method")
self.grade = 0
property_obj = ThisIsMyClass(80)
print(property_obj.get_student_grade())
property_obj.set_student_grade(70)
print(property_obj.get_student_grade())
property_obj.delete_student_grade()
print(property_obj.get_student_grade())
输出:
80
70
This is a delete method
0