Python基础(内置装饰器)

@property:就像访问属性一样和普通访问少了一个(),将函数名作为一个返回值 被装饰的类方法不可回调
@staticmethod: 可以直接通过类名.函数名直接调用被装饰的方法
@classmethod: 可以直接通过类名.函数名直接调用被装饰的方法

class Myclass():
    a=100#类属性
    def __init__(self,height,width):
        self.height=height#实例属性
        self.width=width
    @property #属性装饰器:将函数名作为一个返回值 被装饰的类方法不可回调
    def get_area(self):
    #因为外部可以直接通过实例对象.函数名调用来获得结果 所以必须得有返回值
    #通过类名.函数名调用只能得到该方法的地址 等于下面的cls.get_area
        return self.height*self.width
    @classmethod #类方法装饰器:可以通过类名.函数名直接调用被装饰的方法
    def info(cls):
        print('you can use class attribution and class method!')
        print(cls.a,cls.get_area)#可以通过cls调用类属性和类方法
    @staticmethod#静态装饰器:可以直接通过类名.函数名直接调用被装饰的方法
    def help():
        print('there is no cls and self!')
a=Myclass(20,50)
print('-----------实例化对象.函数名调用----------------')
print(a.get_area)
print('-----------类名.函数名调用----------------')
print(Myclass.get_area)
print('---------实例化对象.函数调用----------')
a.info()
a.help()
print('---------类名.函数直接调用----------')
Myclass.info()
Myclass.help()
        # 输出:
        # >>-----------实例化对象.函数名调用----------------
        # 1000
        # >>---------实例化对象.函数调用----------
        # >>you can use class attribution and class method!
        # >>100 <property object at 0x0000025D9322D958>
        # >>there is no cls and self!
        # >>---------类名.函数直接调用----------
        # >>you can use class attribution and class method!
        # >>100 <property object at 0x0000025D9322D958>
        # >>there is no cls and self!

@staticmethod和@classmethod的区别:
@staticmethod不需要表示自身对象的self和自身类的cls参数,就跟使用函数一样。
@classmethod也不需要self参数,但第一个参数需要是表示自身类的cls参数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值