Python将多个变量初始化为同一个初始值 [英] Python initialize multiple variables to the same initial value

查看:218
本文介绍了Python将多个变量初始化为同一个初始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经解决了这些问题,

<块引用>

  1. Python 将多个变量分配给相同的值?列出行为
    关于元组,我只想变量可以是字符串、整数或字典
  2. 更优雅的多变量声明方式同时
    这个问题有一些我想问的,但接受的答案非常复杂

所以我正在努力实现,

我声明了这个变量,我想把这个声明减少到尽可能少的代码行.

details = Noneproduct_base = 无product_identity = 无category_string = 无store_id = 无image_hash = 无image_link_mask = 无结果 = 无中止 = 错误数据 = {}

什么是最简单、易于维护的?

解决方案

我同意其他答案,但想在这里解释一下重点.

None 对象是单例对象.将 None 对象分配给变量多少次,使用了相同的对象.所以

x = 无y = 无

等于

x = y = 无

但是你不应该对 python 中的任何其他对象做同样的事情.例如,

x = {} # 每次创建一个dict对象y = {}

不等于

x = y = {} # 分配给 x ,y 的相同 dict 对象.我们不应该这样做.

I have gone through these questions,

  1. Python assigning multiple variables to same value? list behavior
    concerned with tuples, I want just variables may be a string, integer or dictionary
  2. More elegant way of declaring multiple variables at the same time
    The question has something I want to ask, but the accepted answer is much complex

so what I'm trying to achieve,

I have this variables declared, and I want to reduce this declarations to as less line of code as possible.

details = None
product_base = None
product_identity = None
category_string = None
store_id = None
image_hash = None
image_link_mask = None
results = None
abort = False
data = {}

What is the simplest, easy to maintain ?

解决方案

I agree with the other answers but would like to explain the important point here.

None object is singleton object. How many times you assign None object to a variable, same object is used. So

x = None
y = None

is equal to

x = y = None

but you should not do the same thing with any other object in python. For example,

x = {}  # each time a dict object is created
y = {}

is not equal to

x = y = {}  # same dict object assigned to x ,y. We should not do this.

这篇关于Python将多个变量初始化为同一个初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆