CuriousPy
CuriousPy

Reputation: 3

Is an instance of a class created immediately inside a list literal?

I created two simple classes with __init__() constructors, and then created instances of them inside a list.

I am curious to know whether simply creating the object inside the list will actually create an instance of that class, or instead, is it only when we later refer to that object (by mentioning the index value) that the class instance is created?

#First Class
class myClassOne(object):
  def __init__(self, a):
    self.a = a
  def __str__(self):
    return self.a

#Second class
class myClassTwo(object):
  def __init__(self, a):
    self.a = a
  def __str__(self):
    return self.a

#Instance of classes being called as an object inside the list
a = [1,2,3,myClassOne("hello"),myClassTwo("world"),"blah","blah"]
print(id(a[3]),id(a[4]))
print(a[3],a[4])

Output:

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
140362290864536 140362290864592
hello world

Upvotes: 0

Views: 41

Answers (1)

schesis
schesis

Reputation: 59158

You can test this easily by adding a few print statements:

class myClassOne:

    def __init__(self, a):
        self.a = a
        print("myClassOne instance created.")

    def __str__(self):
        return self.a


class myClassTwo:

    def __init__(self, a):
        self.a = a
        print("myClassTwo instance created.")

    def __str__(self):
        return self.a


print("Creating list 'a' ...")
a = [1, 2, 3, myClassOne("hello"), myClassTwo("world"), "blah", "blah"]
print("... list 'a' created.")

print("Printing ids ...")
print(id(a[3]), id(a[4]))
print("... ids printed.")

print("Printing items ...")
print(a[3], a[4])
print("... items printed.")

Here's the result of that:

$ python3 hello.py 
Creating list 'a' ...
myClassOne instance created.
myClassTwo instance created.
... list 'a' created.
Printing ids ...
139953120034712 139953120034656
... ids printed.
Printing items ...
hello world
... items printed.

As you can see, the instances are created during the creation of the list a.

This is always the case: when you tell Python to do something, it does it immediately, regardless of whether that instruction is part of the construction of a list or some similar object.

Note that there's a difference between telling Python to do something (as in the case where you're creating that list), and telling it how to do something (as in the case where you're defining myclassOne.__init__().

When you define a function or method with a def ... block, you're telling Python how to do something, and it doesn't actually get done until you call that function or method.

When you build a list, you're telling Python to do something, so it just goes ahead and does it.

Upvotes: 2

Related Questions