python7-类的装饰器(property, classmethod, staticmethod)

1,property

修饰方法,使得方法执行并获取执行结果从而使得方法可以如同属性被调用(被装饰的方法不可以有参数)

'''一个例子'''
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

person1 = Person('xxx', 1997)
print(person1.name)
print(person1.age)  #随着时间的变化这个“人”的年龄在自动增长
'''
进阶,可以要求类中的属性按照自己的要求进行更改,要求:@property修饰的方法,.setter之前的方法,.setter修饰的方法三者同名;deleter相同
本质:
@xxx.setter定义的方法在 类.方法=xxx 时被调用;
@xxx.deleter定义的方法在 del 类.方法 时被调用;
'''
class Goods:
    discount = 0.8
    def __init__(self, name, origin_price):
        self.name = name
        self.__price = origin_price
    @property
    def price(self):
        return self.__price * self.discount
    @price.setter
    def price(self, new_value):
        if isinstance(new_value, int):
            self.__price = new_value
        else:
            print('输入值非法')
    @price.deleter
    def price(self):
        del self.__price
        print('price 被删除')

apple = Goods('apple', 5)
print(apple.price)
apple.price = 'abc'
print(apple.price)
del apple.price
# print(apple.price)    #会报错

2,classmethod

被装饰的方法称为类方法,类方法需要传递cls,cls指被修饰的方法所属的类

'''一个例子'''
class Goods(object):
    __discount = 0.8
    def __init__(self):
        self.__price = 5
        self.price = self.__price * self.__discount
    @classmethod
    def change_discount(cls, new_discount):
        print(cls)
        print(Goods)
        Goods.__discount = new_discount

# Goods.change_discount(0.6)

'''再来一个例子'''
import time
class Date(object):
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day
    @classmethod
    def today(cls):
        todayBackup = time.localtime()
        return cls(todayBackup.tm_year, todayBackup.tm_mon, todayBackup.tm_mday)

today = Date.today()
print(today.year)
print(today.month)
print(today.day)

3,staticmethod

被装饰的方法会成为静态方法,静态方法不需要传参数

'''一个例子'''
class User(object):
    @staticmethod
    def login():
        print('用户登录')
User.login()

user1 = User()
user1.login()

可以定义在类中的:

  1. 静态变量, 所有对象共享,可由类、对象调用,不可重新赋值(重新赋值后是在对象也就是self的命名空间中的)
  2. 绑定方法(self), 对象调用(因为有self)
  3. 类方法(@classmethod、cls), 由类调用(因为由cls)
  4. 静态方法(@staticmethod), 可由类、对象调用
  5. @property属性 由对象调用,不加括号(要想修改和删除需要构建setter和deleter修饰的方法)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tensor_zhang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值