Pass a list to a class python

This question already has an answer here:

  • “Least Astonishment” and the Mutable Default Argument 30 answers

  • This looks like it's happening because you're passing the same list to every object. As a result, all the objects maintain references to the same list, and since list is mutable, it appears to change "all" of them at once.

    To fix this, either pass in a new empty list each time you create a revs object, or else clone the list you're passing in:

    cada = revs(rev, us, list_acct[:])
    

    Note that if list_acct contains mutable objects, you could still get into the same problem again, but one level deeper!

    If you're not passing lists to the revs objects when you create them at all (I can't tell, since you're not showing your full code!), then you have the same problem, but for a different reason: in Python, default arguments are all evaluated once, at the time of the function definition. Therefore, you can get this behavior:

    r1 = revs(1, 1)
    r2 = revs(2, 2)
    r1.accs.append("Hi!")
    print(r1.accs) # prints ['Hi!']
    print(r2.accs) # prints ['Hi!']
    

    Because the default argument for the revs constructor is always pointing to the same list. See this question for an explanation as to why, but to get around it, just use None as your default instead of [] .

    class revs:
        def __init__(self, rev, us, accs=None):
            self.rev = rev
            self.us = us
            if accs is None:
                accs = []
            self.accs = accs
    
    链接地址: http://www.djcxy.com/p/28542.html

    上一篇: Python中的可变默认参数

    下一篇: 将一个列表传递给一个类python