Note that there are some explanatory texts on larger screens.

plurals
  1. POmemory management with objects and lists in python
    primarykey
    data
    text
    <p>I am trying to understand how exactly assignment operators, constructors and parameters passed in functions work in python specifically with lists and objects. I have a class with a list as a parameter. I want to initialize it to an empty list and then want to populate it using the constructor. I am not quite sure how to do it.</p> <p>Lets say my class is --</p> <pre><code>class A: List = [] # Point 1 def __init1__(self, begin=[]): # Point 2 for item in begin: self.List.append(item) def __init2__(self, begin): # Point 3 List = begin def __init3__(self, begin=[]): # Point 4 List = list() for item in begin: self.List.append(item) listObj = A() del(listObj) b = listObj </code></pre> <p>I have the following questions. It will be awesome if someone could clarify what happens in each case --</p> <ol> <li><p>Is declaring an empty like in Point 1 valid? What is created? A variable pointing to NULL?</p></li> <li><p>Which of Point 2 and Point 3 are valid constructors? In Point 3 I am guessing that a new copy of the list passed in (begin) is not made and instead the variable List will be pointing to the pointer "begin". Is a new copy of the list made if I use the constructor as in Point 2?</p></li> <li><p>What happens when I delete the object using del? Is the list deleted as well or do I have to call del on the List before calling del on the containing object? I know Python uses GC but if I am concerned about cleaning unused memory even before GC kicks in is it worth it?</p></li> <li><p>Also assigning an object of type A to another only makes the second one point to the first right? If so how do I do a deep copy? Is there a feature to overload operators? I know python is probably much simpler than this and hence the question.</p></li> </ol> <p>EDIT: 5. I just realized that using Point 2 and Point 3 does not make a difference. The items from the list begin are only copied by reference and a new copy is not made. To do that I have to create a new list using list(). This makes sense after I see it I guess.</p> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload