• python设计模式1:创建型模式


    1.原型模式

    如果想根据现有的对象复制出新的对象并进行修改,可以考虑“原型模式”,而无需知道任何创建细节。(有点像写轮眼...你不需要知道它)

    import copy
    
    class Point:
        __slots__ = ("x","y")
    
        def __init__(self,x,y):
            self.x = x
            self.y = y
    
    point1 = Point(1,2)
    point2 = copy.deepcopy(point1)
    print(point2.x)
    point2.x = 3
    print(point2.x)    #answer:1,3

    2.单例模式

    如果在整个程序运行过程中,某个类只应该有一个实例,那么可通过单例模式来保证。有一种实现单例模式比较简单的办法是:创建模块时,把全局状态放在私有变量中,并提供用于访问此变量的公开函数。

    举个例子,如果我们要实现一个功能,这个功能可以返回含有货币汇率的字典键值对。那么有两种办法可以实现:

    (1)每次调用时先创建字典,然后读取文件,从字典取出值。

    (2)加一个判断的flag,保证在同一个单例下,第一次把字典创建好,以后直接从字典里取值。

    明显(2)好于(1)

    import urllib
    
    _URL = "http://www.banlofcanada.ca/stats/assets/csv/fx-seven-day.csv"
    
    def get(refresh=False):
        if refresh:
            get.rates = {}
        if get.rates:
            return get.rates
        with urllib.request.urlopen(_URL) as file:
            for line in file:
                line = line.rstrip().decode("utf-8")
                if not line or line.startswith(("#","Date")):
                    continue
                name,currency,*rest = re.split(r"s*,s*",line)
                key = "{} ({})".format(name,currency)
                try:
                    get.rates[key] = float(rest[-1])
                except ValueError as err:
                    print("error {}: {}".format(err,line))
        return get.rates
    get.rates={}

    to be continue...

  • 相关阅读:
    LeetCode() Rotate Image
    LeetCode() Sort Colors
    LeetCode() Spiral Matrix
    LeetCode() Find Minimum in Rotated Sorted Array
    LeetCode(169)Majority Element and Majority Element II
    LeetCode(88) Merge Sorted Array
    LeetCode(283) Move Zeroes
    sql临时表和表变量
    自增长字段自定义
    [转]作者:朱 茂海 CentOS安装iRedMail web邮件服务器
  • 原文地址:https://www.cnblogs.com/alexkn/p/4858533.html
Copyright © 2020-2023  润新知