Python class initialization parameter assignment, the instance directly calls the Append function, causes the variable in all instances to change __ function

Source: Internet
Author: User
Problem Description

Just ask a question in the dormitory, simply said that the programming encountered the following situation:

Class Node (object):
    def __init__ (self, childrenlist=[], name = '. '):
        self.name = name
        self.childrenlist = Ch Ildrenlist
A = node (name = ' WJ ')
B = node ()
a.childrenlist.append (1)
print (a.childrenlist)
Print (b.childrenlist)

The output is as follows:

[1]
[1]
reason

Strangely, the assignment of instance a causes the variable childrenlist in B to change.

Intuitively, it should be a function parameter assignment is a value or a reference to pass the problem, of course, in essence or the value of the transfer, but the assignment object is variable or immutable problem.

So, to test:

Class Node (object):
    def __init__ (self, childrenlist=[], name = '. '):
        self.name = name
        self.childrenlist = Ch Ildrenlist
        Print ("Childrenlist", ID (self.childrenlist))
        print ("name", ID (self.name))
a = Node (name = ' WJ ')
B = Node ()
a.childrenlist.append (1)
print (a.childrenlist)
print (b.childrenlist)

Results

Childrenlist 2754369477512
name 2754369477232
childrenlist 2754369477512
name 2754335175152

As you can see, the name string differs in memory locations in two instances, but the childrenlist is the same, and the result in 1 appears. Modify

The simplest way to assign a value directly by using self.childrenlist=[is to not use the value in the parameter.

A better way to use Python's deep copy.

Import copy
class Node (object):
    def __init__ (self, childrenlist=[], name = '. '):
        self.name = name
        Self.childrenlist = Copy.deepcopy (childrenlist)
a = node (name = ' WJ ')
B = node ()
a.childrenlist.append (1) C7/>print (a.childrenlist)
print (b.childrenlist)

In this way, the childrenlist in the generated instance will point to different units.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.