python中property属性_Python中property属性实例解析

本文主要讲述的是对Python中property属性(特性)的理解,具体如下。

定义及作用:

在property类中,有三个成员方法和三个装饰器函数。

三个成员方法分别是:fget、fset、fdel,它们分别用来管理属性访问;

三个装饰器函数分别是:getter、setter、deleter,它们分别用来把三个同名的类方法装饰成property。

fget方法用来管理类实例属性的获取,fset方法用来管理类实例属性的赋值,fdel方法用来管理类实例属性的删除;

getter装饰器把一个自定义类方法装饰成fget操作,setter装饰器把一个自定义类方法装饰成fset操作,deleter装饰器把一个自定义类方法装饰成fdel操作。

只要在获取自定义类实例的属性时就会自动调用fget成员方法,给自定义类实例的属性赋值时就会自动调用fset成员方法,在删除自定义类实例的属性时就会自动调用fdel成员方法。

下面从三个方面加以说明

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属性实例解析的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

您可能感兴趣的文章:

python @property的用法及含义全面解析

Python解析json之ValueError: Expecting property name enclosed in double quotes: line 1 column 2(char 1)

实例讲解Python编程中@property装饰器的用法

Python黑魔法@property装饰器的使用技巧解析

Python Property属性的2种用法

介绍Python的@property装饰器的用法

Python中用Descriptor实现类级属性(Property)详解

python的描述符(descriptor)、装饰器(property)造成的一个无限递归问题分享

时间: 2018-02-09

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值