要了解@property的用法,必选先知道在类里面变量的区别
class People(object):
def __init__(self, name, age, number):
self.name = name
self.age = age
self.__number = number # 私有属性
首先定义一个People类,这里name和age是可以从外部被访问的,而number不行,number是私有变量。
>>> people = People(name='Tom', age=23, number=0)
>>> people.name
'Tom'
>>> people.age
23
>>> people.number
Traceback (most recent call last):
File "" , line 1, in <module>
people.number
AttributeError: 'People' object has no attribute 'number'
为了能够从外部访问,并操作私有变量,有了@Property这玩意。
1、访问
对上面代码进行修改
class People(object):
def __init__(self, name, age, number):
self.name = name
self.age = age
# 私有属性
self.__number = number
@property
def number(self):
return self.__number # 返回私有属性值
此时,私有变量number,可以被访问了。
>>> people = People(name='Tom', age=23, number=0)
>>> people.number
0
2、赋值
上面的代码,只能访问,不能赋值,再增加。
class People(object):
def __init__(self, name, age, number):
self.name = name
self.age = age
# 私有属性
self.__number = number
@property
def number(self):
return self.__number # 返回私有属性值
@number.setter
def number(self, value):
self.__number = value # 设置__number的值
此时,私有变量number可以被访问, 也可以被修改了!
>>> people = People(name='Tom', age=23, number=0)
>>> people.number
0
>>> people.number = 3
>>> people.number
3
3、删除
再增加一个功能删除
class People(object):
def __init__(self, name, age, number):
self.name = name
self.age = age
# 私有属性
self.__number = number
@property
def number(self):
return self.__number # 返回私有属性值
@number.setter
def number(self, value):
self.__number = value # 设置__number的值
@number.deleter
def number(self):
del self.__number # 删除属性
此时number可以被访问,被修改,被删除
>>> people = People(name='Tom', age=23, number=0)
>>> people.number
0
>>> del people.number
>>> people.number
Traceback (most recent call last):
File "" , line 1, in <module>
people.number
File "C:\Users\Lenove\Desktop\tx.py", line 10, in number
return self.__number # 返回私有属性值
AttributeError: 'People' object has no attribute '_People__number'