property属性

一、定义

  • 一种用起来像是使用的实例属性一样的特殊属性,可以对应于某个方法
    例子:
class Person(object):
    @property
    def run(self):
        pass

p = Person()
print(p.run)  #打印property属性

二、property属性的两种方式

1. 装饰器 即:在方法上应用装饰器

  • 在类的实例方法上应用@property装饰器
    Python中的类有经典类和新式类,新式类的属性比经典类的属性丰富。( 如果类继object,那么该类是新式类 )
1.1 经典类,具有一种@property装饰器
class Person:

    def __init__(self,money):
        self.money = money

    @property
    def get_money(self):
        return self.money

p = Person(3000)
print(p.get_money)
1.2 新式类,具有三种@property装饰器
class Goods(object):
    def __init__(self):
        #原价
        self.origin_price = 100
        #折扣
        self.discount = 0.8

    @property
    def price(self):
        return self.origin_price * self.discount

    @price.setter
    def price(self,value):
        self.origin_price = value

    @price.deleter
    def price(self):
        del self.origin_price

good = Goods()
print('获取商品价格为:%s' % good.price) #80
good.price = 80
print('修改后获取商品价格为:%s' % good.price) #64
del good.price #删除商品价格
# print('删除后获取商品价格为:%s' % good.price)

2. 类属性方式,创建值为property对象的类属性

  • 当使用类属性的方式创建property属性时,经典类和新式类无区别
class Goods(object):
    def __init__(self):
        #原价
        self.origin_price = 100
        #折扣
        self.discount = 0.8

    def get_price(self):
        return self.origin_price * self.discount

    def set_price(self,value):
        self.origin_price = value

    def del_price(self):
        print('删除商品价格')
        del self.origin_price

    price = property(get_price,set_price,del_price,'属性的描述信息')


good = Goods()
print('获取商品价格为:%s' % good.price) #80
good.price = 80
print('修改后获取商品价格为:%s' % good.price) #64
desc = Goods.price.__doc__
print('商品的描述信息是:%s' % desc)
del good.price #删除商品价格
# # print('删除后获取商品价格为:%s' % good.price)

property方法中有个四个参数:
- 第一个参数是方法名,调用 对象.属性 时自动触发执行方法
- 第二个参数是方法名,调用 对象.属性 = XXX 时自动触发执行方法
- 第三个参数是方法名,调用 del 对象.属性 时自动触发执行方法
- 第四个参数是字符串,调用 对象.属性.doc ,此参数是该属性的描述信息

由于类属性方式创建property属性具有3种访问方式,我们可以根据它们几个属性的访问特点,分别将三个方法定义为对同一个属性:获取、修改、删除

三、私有属性添加getter和setter方法

  1. 装饰器
#1.装饰器
class Money(object):
    def __init__(self):
        self.__money = 100

    @property
    def money(self):
        return self.__money

    @money.setter
    def money(self,value):
        self.__money = value


mon = Money()
mon.money = 200
print(mon.money)

2.类属性

#2.类属性
class Money(object):
    def __init__(self):
        self.__money = 100

    def get_money(self):
        return self.__money

    def set_money(self,value):
        self.__money = value

    money = property(get_money,set_money)


mon = Money()
mon.money = 300
print(mon.money)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值