Problem with Python __init__

I have some problems understanding what is happening with the arguments to the init class, which are lists like:

class A(object):
    def __init__(self, argument=[]):  
        self.argument = argument[:]  

or

def __init__(self,argument=None):  
    self.arguments = arguments or []  

or

def __init__(self, argument=[]):  
    self.argument = argument  

This cannot be done because the default value for each object Apoints to the same piece of memory. I can’t understand what is happening here and how it is happening.

+3
source share
3 answers

This is the well-known python gotcha .

, , , ( ), , .

- , :

def __init__(self, arguments=None):  
    self.arguments = arguments or []

, , , Python .

:

def my_function(*args):
    print args

. , :

>>> my_function(1, 2, 3)

:

(1, 2, 3)

, oposite , , ( ), . :

>>> my_list = [1, 2, 3]
>>> my_function(*my_list)

, , , .

, , , .

+6

, .

+4

, , , , init , , , . , , .

, : Python. Python. :

a = [1,2,3]
b = a

You do not set bto a value a. You set bto reference the same object. So the statement:

a is b

It is true because the names refer to the same object.

a = [1,2,3]
b = [1,2,3]
a is b

This will return false. The reason is that now you have created two different objects. So the line:

self.argument = argument[:]

is a (necessary) way to make a copy self.argumentso that it does not refer to the same object.

+1
source

Source: https://habr.com/ru/post/1730726/


All Articles