美文网首页
property属性

property属性

作者: 潇潇雨歇_安然 | 来源:发表于2018-05-25 16:30 被阅读0次

一、定义

  • 一种用起来像是使用的实例属性一样的特殊属性,可以对应于某个方法
    例子:
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)

相关文章

网友评论

      本文标题:property属性

      本文链接:https://www.haomeiwen.com/subject/yakujftx.html