Python initialize multiple variables to the same initial value

℡╲_俬逩灬. 提交于 2019-11-30 17:43:49

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.

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 = {}

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.

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)]

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?

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