Python initialize multiple variables to the same initial value

前端 未结 6 1409
不思量自难忘°
不思量自难忘° 2020-12-14 06:47

I have gone through these questions,

  1. Python assigning multiple variables to same value? list behavior
    concerned with tuples, I want
相关标签:
6条回答
  • 2020-12-14 07:22

    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)]
    
    0 讨论(0)
  • 2020-12-14 07:33

    A mix of previous answers :

    def default(number, value = None):
        return [value] * number
        
    o, p, q, r, s = default(5)
    t, u = default(2, false)
    v, w, x = default(3, {})
    y, z = default(2, 0)
    
    0 讨论(0)
  • 2020-12-14 07:39

    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.
    
    0 讨论(0)
  • 2020-12-14 07:45

    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 = {}
    
    0 讨论(0)
  • 2020-12-14 07:46

    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.

    0 讨论(0)
  • 2020-12-14 07:48

    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?

    0 讨论(0)
提交回复
热议问题