python

本文探讨了Python中单例模式的实现,通过重写new方法确保类的唯一实例,并介绍了装饰器的使用,包括如何用装饰器记录函数执行时间和次数,以及工厂模式下不同汽车品牌的创建。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# -*- coding: UTF-8 -*-
# 单例模型
# 重写new方法
class Mysingleton(object):
    __obj = None
    __init_flag = True

    def __new__(cls, *args, **kwargs):
        if cls.__obj == None:
            cls.__obj = super(Mysingleton, cls).__new__(cls, *args, **kwargs)
            # cls.__obj = object.__new__(cls)
        return cls.__obj

    def __init__(self, name):
        if Mysingleton.__init_flag:
            print '666666'
            self.name = name
            Mysingleton.__init_flag = False

a = Mysingleton('aa')
b = Mysingleton('bb')

print a
print b

# 用装饰器实现
from functools import wraps

def my_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        '''decorator'''
        print('Decorated function...')
        return func(*args, **kwargs)

    return wrapper

@my_decorator
def test():
    '''Testword'''
    print('Test function')

print(test.__name__, test.__doc__)

# 工厂模式
class Factory(object):
    def create_car(self, brand, *args, **kwargs):
        if brand == '奔驰':
            return Benz(*args, **kwargs)
        elif brand == '宝马':
            return BMW(*args, **kwargs)
        elif brand == '比亚迪':
            return BYD(*args, **kwargs)
        else:
            return '未知品牌,无法创建'

class Benz(object):
    def __init__(self, clour):
        self.clour = clour

    def car(self):
        print '这辆奔驰是{}颜色的'.format(self.clour)
    pass
class BMW(object):
    def __init__(self, clour):
        self.clour = clour

    def car(self):
        print '这辆宝马是{}颜色的'.format(self.clour)

class BYD(object):
    def __init__(self, clour):
        self.clour = clour

    def car(self):
        print '这辆比亚迪是{}的'.format(self.clour)

factory = Factory()
car1 = factory.create_car('宝马', '红色')
car1.car()
#   写一个装饰器,用于打印函数执行时长及执行次数
import time

def decorator(func):
    count = 0
    def deco(*args, **kwargs):
        # nonlocal count
        start_time = time.time()
        data = func(*args, **kwargs)
        end_time = time.time()
        dt = end_time - start_time
        print '本次调用花费时间{}秒,本次调用为第{}次。'.format(dt, count)
        count += 1
        return data
    return deco

@decorator
def func(n):
    print 'hello world', n
    time.sleep(1)
    
if __name__ == '__main__':
    for i in range(3):
        func(i)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值