首页 > 其他 > 详细

类的三大装饰器之property

时间:2020-08-21 16:10:48      阅读:61      评论:0      收藏:0      [点我收藏+]
# property:

import math
class Circle(object):
    def __init__(self, r):
        self.r = r

    @property  # 把一个方法伪装成一个属性,调用这个方法时不需要加括号就直接得到返回值
    def area(self):
        return math.pi * self.r**2

c = Circle(5)
print(f半径:{c.r}, 面积:{c.area})


import time
class Person(object):
    def __init__(self, name, birth):
        self.name = name
        self.birth = birth

    @property
    def age(self):  # 所以装饰的这个方法不能有参数
        return time.localtime().tm_year - self.birth

TB = Person(太白, 1998)
print(TB.age)


# property的第二个应用场景:和私有属性合作的
class User(object):
    def __init__(self, user, pwd):
        self.user = user
        self.__pwd = pwd

    @property
    def pwd(self):
        return self.__pwd

alex = User(alex, 123)
print(alex.pwd)


# property进阶:
class Goods(object):
    discount = 0.8

    def __init__(self, name, oringin_price):
        self.name = name
        self.__price = oringin_price

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

    @price.setter
    def price(self, new_price):
        print(调用我了---)
        if isinstance(new_price, int):
            self.__price = new_price

    @price.deleter
    def price(self):
        print(执行我了)
        del self.__price


apple = Goods(apple, 5)
print(apple.price) # 查看被@property装饰的price函数

apple.price = 10  # 调用的是被setter装饰的price
print(apple.price)

# del apple.price  # 调用的是被deleter装饰的price,而这里只是调用方法,要在方法内部执行删除
# print(apple.price)

 

类的三大装饰器之property

原文:https://www.cnblogs.com/GOD-L/p/13541033.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!