Python中的只读属性
先决条件: Python类和对象
类是用户定义的蓝图或原型,从中创建对象。类提供了一种将数据和功能捆绑在一起的方法。创建一个新类会创建一种新类型的对象,允许创建该类型的新实例。简单来说,让我们假设一个类Student ,一个学生可以有许多属性,如姓名、课程、学生 ID 等。现在假设我们有一个名为 Anita 正在攻读 MBA 的学生,Anita 是一个类的对象学生。
例子:
class student:
def __init__(self, name, course):
self.name = name
self.course = course
def studentid(self):
return "student's identification number is \
{}{}".format(self.name, self.course)
student1 = student("Anita", "MBA")
print(student1.studentid())
输出:
student's identification number is AnitaMBA
现在,我们希望将学生 ID 作为属性而不是方法来访问。为此,只需在方法之前添加@property装饰器。
例子:
class student:
def __init__(self, name, course):
self.name = name
self.course = course
@property
def studentid(self):
return "student's identification number is \
{}{}".format(self.name, self.course)
student1 = student("Anita", "MBA")
print(student1.studentid)
输出:
student's identification number is AnitaMBA
只读属性是没有设置器的属性装饰器。这里的学生 ID 是只读属性,因为它没有设置器。一般而言,这意味着该值是不可更改的。为了理解,让我们再举一个例子:
例子:
class employee:
def __init__(self, basesalary, yearsofworking):
self.basesalary = basesalary
self.yearsofworking = yearsofworking
@property
def salary(self):
self.salary = 50000
amit = employee(20000, 5)
amit.salary = 10000
print(amit.basesalary, amit.yearsworking, amit.salary)
输出:
Traceback (most recent call last):
File “/home/e029e0b9ccad85905e22dd5a91943897.py”, line 14, in
amit.salary = 10000
AttributeError: can’t set attribute
要解决此问题,将在此代码中添加一个 setter。完成此操作后,它将不再是只读属性。
例子:
class employee:
def __init__(self, basesalary, yearsofworking):
self.basesalary = basesalary
self.yearsofworking = yearsofworking
self._salary = 0
@property
def salary(self):
return self._salary
@salary.setter
def salary(self, salary):
self._salary = salary
amit = employee(20000, 5)
amit.salary = 10000
print(amit.basesalary, amit.yearsofworking, amit.salary)
输出:
20000 5 10000