Python initialize multiple variables to the same initial value

爷,独闯天下 提交于 2019-12-30 05:46:09

问题


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 ?


回答1:


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.



回答2:


First of all I would advice you not to do this. It's unreadable and un-Pythonic. However you can reduce the number of lines with something like:

details, product_base, product_identity, category_string, store_id, image_hash, image_link_mask, results = [None] * 8
abort = False
data = {}



回答3:


details, producy_base, product_identity, category_string, store_id, image_hash, image_link_mask, results = None, None, None, None, None, None, None, None; abort = False; data = {}

That's how I do.




回答4:


I have a one-line lambda function I use that helps me out with this.

nones = lambda n: [None for _ in range(n)]
v, w, x, y, z = nones(5)

The lambda is the same thing as this.

def nones(n):
    return [None for _ in range(n)]



回答5:


This does not directly answer the question, but it is related -- I use an instance of an empty class to group similar attributes, so I do not have to clutter up my init method by listing them all.

class Empty:
    pass

class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.w = Empty()          # widgets
        self.master = master
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.w.entry = tk.Entry(self, bg="orange", fg="black", font=FONT)

What is the difference between SimpleNamespace and empty class definition?




回答6:


A mix of previous answers :

def default(value, number):
    return [value] * number

v, w, x, y, z = default(20, 5)


来源:https://stackoverflow.com/questions/33331732/python-initialize-multiple-variables-to-the-same-initial-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!