本文主要讲述的是对Python中property属性(特性)的理解,具体如下。
定义及作用:
下面从三个方面加以说明
Num01?>原始的getter和setter方法,获取私有属性值
# 定义一个钱的类
class Money(object):
def __init__(self):
self._money = 0
def getmoney(self):
return self._money
def setmoney(self, value):
if isinstance(value, int):
self._money = value
else:
print("error:不是整型数字")
money = Money()
print(money.getmoney())
# 结果是:0
print("====修改钱的大小值====")
money.setmoney(100)
print(money.getmoney())
# 结果是:100
Num02?>使用property升级getter和setter方法
# 定义一个钱的类
class Money(object):
def __init__(self):
self._money = 0
def getmoney(self):
return self._money
def setmoney(self, value):
if isinstance(value, int):
self._money = value
else:
print("error:不是整型数字")
money = property(getmoney, setmoney)
money = Money()
print(money.getmoney())
# 结果是:0
print("====修改钱的大小值====")
money.setmoney(100)
print(money.getmoney())
# 结果是:100
#最后特别需要注意一点:实际钱的值是存在私有便令__money中。而属性money是一个property对象,
是用来为这个私有变量__money提供接口的。
#如果二者的名字相同,那么就会出现递归调用,最终报错。
Num03?>使用property取代getter和setter
@property成为属性函数,可以对属性赋值时做必要的检查,并保证代码的清晰短小
# 定义一个钱的类
class Money(object):
def __init__(self):
self._money = 0
@property
# 注意使用@property装饰器对money函数进行装饰,就会自动生成一个money属性,
当调用获取money的值时,就调用该函数
def money(self):
return self._money
@money.setter
# 使用生成的money属性,调用@money.setter装饰器,设置money的值
def money(self, value):
if isinstance(value, int):
self._money = value
else:
print("error:不是整型数字")
aa = Money()
print(aa.money)
# 结果是:0
print("====修改钱的大小值====")
aa.money = 100
print(aa.money)
# 结果是:100
总结
以上就是本文关于Python中property属性实例解析的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!