Python之面向对象装饰器(02)

发布时间:2021-12-03 公开文章

I am not a designer nor a coder. I'm just a guy with a point-of-view and a computer.

筑基<融合<元婴<分神<渡劫<大乘

 


类与装饰器

装饰器入门

import math, pprint

# 定义类
class Circle:

    cnt = 0 #类变量

    #__init__ 初始化对象    
    def __init__(self, radius = 15):
        self.radius = radius        
        Circle.cnt +=1

    def calcPerimeter(self):
        return 2 * self.radius * math.pi    

    def roundArea(self):
        return self.radius * self.radius * math.pi

#创建对象, 传入半径值
oneR = Circle()
print('圆的半径:', oneR.radius)
twoR = Circle(13)
print('圆的半径:', twoR.radius)
print('创建了{0}个对象'.format(Circle.cnt))

print('Circle.__name__ : ', Circle.__name__)
print('Circle.__doc__ : ', Circle.__doc__)
print('Circle.__module__ : ', Circle.__module__)
圆的半径: 15
圆的半径: 13
创建了2个对象
Circle.__name__ :  Circle
Circle.__doc__ :  None
Circle.__module__ :  __main__
#使用简单的

def discount(price): #定义装饰器函数
    if price() >= 500.0:        
        return lambda: price() * 0.9
    else:
        return lambda: price()

@discount #装饰器
def Entirely(): #购物金额
    return 555.0

print('合计:', Entirely())
合计: 499.5
#简单的装饰器 -- 两数相加
def plusNumbers(x, y):
    return x**2 + y**2

#两数相减
def minusNumbers(x, y):
    return x**2 - y**2

a, b = eval(input('Two numbers:'))
print('两数平方和:', plusNumbers(a, b))
print('两数平方差:', minusNumbers(a, b))
Two numbers:2,3
两数平方和: 13
两数平方差: -5
#定义装饰器
def outerNums(func):
    def inner(x, y):
        x, y = eval(input('Two numbers:'))
        return func(x, y)
    return inner

@outerNums
def plusNumbers(x, y):
    return x**2 + y**2

@outerNums
def minusNumbers(x, y):
    return x**2 - y**2

a, b = 0, 0
print('平方和:', plusNumbers(a, b))
print('平方差:', minusNumbers(a, b))
Two numbers:2,2
平方和: 8
Two numbers:2,3
平方差: -5
'''装饰器 -- 定义 Decorator
    *args -- 收集位置参数,**kw -- 收集关键字参数
'''
import time, functools

def Records(some_func): #装饰器   
    @functools.wraps(some_func)    
    def inner(*args, **kw): #返回函数
        print('Hi! 调用了{}()'.format(
            some_func.__name__))
        return some_func(*args, **kw)            
    return inner    

@Records #装饰器
def Atonce():
    #将获取时间进行格式化
    return time.strftime('%Y-%b-%d %H:%M:%S',
        time.localtime())

#调用函数
print('登录时间:', Atonce())
Hi! 调用了Atonce()
登录时间: 2019-Aug-28 21:51:29
#含有参数的装饰器 -- 定义 Decorator
import time, functools

def Records(name): #修饰器    
    def Person(some_func):
        #@functools.wraps(some_func)
        def inner(*args, **kw):
            print('Hi! {}, 调用了{}()'.format(
                name, some_func.__name__))
            #print('Hi!', name)
            return some_func(*args, **kw)            
        return inner #返回函数
    return Person

@Records('Joson')#含有参数的装饰器
def Atonce():
    #将获取时间执行格式化操作
    return time.strftime('%Y-%b-%d %H:%M:%S',
        time.localtime())

#调用函数
print('登录时间:', Atonce())
Hi! Joson, 调用了Atonce()
登录时间: 2019-Aug-28 21:54:30

使用函数来装饰类

#使用函数来装饰类
def Car(status):#装饰器,以类来传入
    class Motor:
        def __init__(self, name):#初始化对象
            self.title = name #车款
            self.obj = status()#获取传入的实例化对象
            print('车款:', self.title)

        def tint(self, opt):#获取颜色
            return self.obj.tint(opt)

        def power(self, rmp):#获取排气量
            return self.obj.power(rmp)
    return Motor

@Car #装饰器, Equip = Car(Equip)
class Equip:
    def tint(self, opt):        
        if opt == 1:
            hue = '炫魅红'               
        elif opt == 2:
            hue = '极光蓝'
        elif opt == 3:
            hue = '云河灰'
        return hue

    def power(self, rmp):
        if rmp == 4:
            return 1600
        elif rmp == 5: 
            return 1800

op1, op2 = eval(input(
    '选择颜色:1..红, 2.蓝色, 3.灰色 \n' + 
    '排气量:4.1600, 5.1800...'))

hybrid = Equip('Yaris')

print('你选择的颜色:{}, 排气量 {}'.format(
    hybrid.tint(op1), hybrid.power(op2)))
选择颜色:1.., 2.蓝色, 3.灰色 
排气量:4.1600, 5.1800...1,4
车款: Yaris
你选择的颜色:炫魅红, 排气量 1600
#使用staticmethod方法

class Motor:#定义类
    @staticmethod #将equip()方法修饰为静态方法
    def equip(name, seats):
        print('车款', name, '座位数', seats)

car = Motor()#创建对象
Motor.equip('SUV', 7)#用类调用类方法
car.equip('altis', 4)#用对象调用对象方法
车款 SUV 座位数 7
车款 altis 座位数 4
#使用 @classmethod, @staticmethod

class Motor:
    count = 0#类属性统计对象

    def __init__(self):
       Motor.count += 1#计算对象个数

    @classmethod #类方法
    def equip(cls, rmp, seats):#cls为类本身
        print('排气量', rmp, '座位数', seats)

    @staticmethod #静态方法
    def display():
        print('有', Motor.count, '个对象')

car = Motor()#创建第1个对象
car.equip(1500, 4)#用对象调用方法

hybird = Motor()#第2个对象
hybird.equip(2000, 7)

juddy = Motor()#第3个对象
Motor.equip(1800, 5)#用类调用方法

Motor.display()#统计对象数
排气量 1500 座位数 4
排气量 2000 座位数 7
排气量 1800 座位数 5
 3 个对象