第十五章 装饰器相关函数

1. 【把一个方法封装成类方法】classmethod()函数

语法参考

classmethod()函数的语法格式有2种形式。

第一种:

classmethod(function)
  • function:方法名

第二种:

@classmethod
    def f(cls, arg1, arg2, ...): ...
  • 参数:无。

  • 返回值:返回函数的类方法。

说明:通常使用第二种用法。

锦囊01 使用classmethod()函数设置类方法

使用classmethod()函数设置类方法,代码如下:

class Student:
    age = 18
    
    def printAge(cls):
        print('The age is:', cls.age)

Student.printAge = classmethod(Student.printAge) 		# 创建类的方法
Student.printAge() 										# 调用类的方法

上述代码中,定义了一个Student类,它有一个age类属性和printAge()方法。值得注意的是printAge()函数第一个参数是cls而不是self,它表示类对象不是实例对象。然后调用classmethod()函数将printAge方法设置为类方法。

锦囊02 使用@classmethod装饰器设置类的方法

使用@classmethod将方法设置为类方法,代码如下:

class A(object):
    bar = 1

    def func1(self):
        print('func1')

    @classmethod
    def func2(cls):
        print('func2')
        print(cls.bar)
        cls().func1()  		# 调用 foo 方法

A.func2()  					# 不需要实例化

锦囊03 继承父类的类方法

创建一个父类A,它有一个类方法。类B继承A,并调用父类A的类方法。代码如下:

class A:
    @classmethod
    def get_age(cls,age):
        """定义类方法"""
        return 'The age is:{}'.format(age)

class B(A):
    pass

print(B.get_age(18))  			# 调用父类的类方法

2. 【获取属性值】property()函数

语法参考

property()函数的语法格式如下:

class property([fget[, fset[, fdel[, doc]]]])

参数说明:

  • fget:获取属性值的函数;

  • fset:设置属性值的函数;

  • fdel:删除属性值函数;

  • doc:属性描述信息。

  • 返回值:返回类的属性。

锦囊01 获取实例对象的属性值

使用property()函数获取类的属性值,代码如下:

class Student:

    def __init__(self, value):
        self._value = value

    def getValue(self):
        print('Getting value')
        return self._value

    def setValue(self, value):
        print('Setting value to ' + value)
        self._value = value

    def delValue(self):
        print('Deleting value')
        del self._value

    value = property(getValue, setValue, delValue, )

s = Student('Andy')
print(s.value)

s.value = 'Jack'
del s.value

上述代码中,s是Student的实例,s.value将调用getter方法,s.x = value 将调用setter, del s.x 将调用deleter。

说明:如果给出,doc 将成为该 property 属性的文档字符串。 否则该 property 将拷贝 fget 的文档字符串(如果存在)。

锦囊02 使用@property获取装饰器

特征属性对象具有 getter, setter 以及 deleter 方法,它们可用作装饰器来创建该特征属性的副本,并将相应的访问函数设为所装饰的函数。代码如下:

class Student:

    def __init__(self, value):
        self._value = value

    @property
    def value(self):
        print('Getting value')
        return self._value

    @value.setter
    def value(self, value):
        print('Setting value to ' + value)
        self._value = value

    @value.deleter
    def value(self):
        print('Deleting value')
        del self._value


s = Student('Andy')
print(s.value)

s.value = 'Jack'
del s.value

锦囊03:创建用于计算的属性

在Python中,可以通过@property(装饰器)将一个方法转换为属性。将方法转换为属性后,可以直接通过方法名来访问方法,而不需要再添加一对小括号“()”,这样可以让代码更加简洁。代码如下:

class Rect:
    def __init__(self,width,height):
        self.width = width                	# 矩形的宽
        self.height = height              	# 矩形的高

    @property                           	# 将方法转换为属性
    def area(self):                     	# 计算矩形的面积的方法
        return self.width*self.height  		# 返回矩形的面积

rect = Rect(800,600)                    	# 创建类的实例
print("面积为:",rect.area)            		# 输出属性的值

3. 【标示方法为静态方法的装饰器】staticmethod()函数

语法参考

staticmethod()函数的语法格式有2种形式。

第一种:

staticmethod(function)

参数:

  • function:方法名

第二种:

@staticmethod
    def f(cls, arg1, arg2, ...): ...
  • 参数:无。

  • 返回值:返回函数的静态方法。

说明:通常使用第二种用法。

锦囊01 使用classmethod()函数设置静态方法

使用classmethod()函数设置静态方法,代码如下:

class Mathematics:
    def addNumbers(x, y):
        return x + y

# 创建addNumbers静态方法
Mathematics.addNumbers = staticmethod(Mathematics.addNumbers)
print('The sum is:', Mathematics.addNumbers(5, 10))

注意:addNumbers()静态方法的参数没有self或cls。

锦囊02 使用@staticmethod装饰器设置静态方法

使用@classmethod将方法设置为静态方法,代码如下:

class Dates:

    @staticmethod
    def toDashDate(date):
        """用户转换日期的静态方法"""
        return date.replace("/", "-") 				# 将日期中的"/"转化为"-"

dateString = "2019/06/18"
dateWithDash = Dates.toDashDate(dateString) 		# 调用静态方法
print('转化后的日期为:{}'.format(dateWithDash))

说明:使用自定义函数的方式同样可以实现日期转换的功能,但是由于日期转换的功能与Dates类关联性较大,所以,通常将其作为静态函数使用。

锦囊03 继承父类的静态方法

创建一个父类Dates,它有一个静态方法。类DatesWithSlashes继承Dates,并调用父类Dates的静态方法。代码如下:

class Dates:

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

    @staticmethod
    def toDashDate(date):
        '''设置静态方法用于转换日期格式'''
        return date.replace("/", "-")

class DatesWithSlashes(Dates):
    def getDate(self):
        return Dates.toDashDate(self.date) 					# 调用父类静态方法

dateFromDB = DatesWithSlashes("2019/06/18") 				# 实例化DatesWithSlashes类
print('转化后的日期为:{}'.format(dateFromDB.getDate())) 		# 调用用getDate()方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值