代码之家  ›  专栏  ›  技术社区  ›  David542

获取或创建函数/方法

  •  0
  • David542  · 技术社区  · 6 年前

    get_or_create 方法。例如,要创建新客户:

    get_or_create_customer(email='hello@example.com')
    

    我见过这样的方法 None ,返回 <item> (True, <item>)

    有没有一个建议的做法,什么回报在一个 获取或创建 方法?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Nicholas Kemp    6 年前

    以你为例,我的方法是:

    #Returns a tuple where the first item is "False" if the email already exists in database, 
    #and "True" if it doesn't and it was appended to the database. The second item is the email.
    
    def get_or_create_customer (email , database): #email as String, database as list
        if email in database:
            return (False, email)
        else:
            database.append(email)
            return (True, email)
    

    测试代码:

    database = ["hello@gmail.com"]
    
    print (get_or_create_customer("hello@gmail.com", database), database)
    >> (False, 'hello@gmail.com') ['hello@gmail.com']
    
    print (get_or_create_customer("example@gmail.com", database), database)
    >> (True, 'example@gmail.com') ['hello@gmail.com', 'example@gmail.com']