是否在列表文字中立即创建了类的实例?

问题描述 投票:0回答:1

我用__init__()构造函数创建了两个简单的类,然后在列表中创建它们的实例。

我很想知道简单地在列表中创建对象是否会实际创建该类的实例,或者只是当我们稍后引用该对象(通过提及索引值)创建类实例时?

#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])

输出:

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
140362290864536 140362290864592
hello world
python python-3.x list class instantiation
1个回答
2
投票

您可以通过添加一些print语句来轻松测试:

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.")

这是结果:

$ 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.

如您所见,实例是在创建列表a期间创建的。

情况总是如此:当你告诉Python做某事时,它会立即执行,无论该指令是否构成列表或类似对象的一部分。

请注意,告诉Python执行某些操作(如您正在创建该列表的情况),并告诉它如何执行某些操作(如您正在定义myclassOne.__init__()的情况)。

当您使用def ...块定义函数或方法时,您告诉Python如何执行某些操作,并且在您调用该函数或方法之前它实际上不会完成。

当你构建一个列表时,你告诉Python要做一些事情,所以它只是继续并且做到了。

© www.soinside.com 2019 - 2024. All rights reserved.