欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python中property属性实例解析

时间:2021-02-04 11:37:00|栏目:Python代码|点击:

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

定义及作用:

在property类中,有三个成员方法和三个装饰器函数。
三个成员方法分别是:fget、fset、fdel,它们分别用来管理属性访问;
三个装饰器函数分别是:getter、setter、deleter,它们分别用来把三个同名的类方法装饰成property。
fget方法用来管理类实例属性的获取,fset方法用来管理类实例属性的赋值,fdel方法用来管理类实例属性的删除;
getter装饰器把一个自定义类方法装饰成fget操作,setter装饰器把一个自定义类方法装饰成fset操作,deleter装饰器把一个自定义类方法装饰成fdel操作。
只要在获取自定义类实例的属性时就会自动调用fget成员方法,给自定义类实例的属性赋值时就会自动调用fset成员方法,在删除自定义类实例的属性时就会自动调用fdel成员方法。

下面从三个方面加以说明

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

上一篇:如何利用pygame实现简单的五子棋游戏

栏    目:Python代码

下一篇:Nginx+Uwsgi+Django 项目部署到服务器的思路详解

本文标题:Python中property属性实例解析

本文地址:http://www.codeinn.net/misctech/57034.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有