如何获得在 Python 中创建类实例的顺序?

这就是我想要做的。我正在尝试制作一个创建Note由NoteBlocks 组成的笔记应用程序。人们通常会Note从第一个块创建到最后一个块,所以我想以某种方式按创建顺序对类实例进行排序。


有没有办法以某种方式获取实例的创建数量?我创建的第一个实例有 1,第二个有 2,依此类推。


或者,我已经想到了另一种方法来做到这一点。如果我能以某种方式使新创建NoteBlock的块指向已创建的前一个块,我将能够像简单的链表一样对它们进行排序。


我能想到的最糟糕的方法是给每个实例一个物理self.created_at属性,以便在创建时对其进行排序,但我认为这是一种愚蠢的方法,希望还有另一种方法。


鉴于我的情况,你建议我做什么?


from datetime import datetime


Class NoteBlock():

  def __init__(self):

    self.contents = None

    self.previous = None

    self.created_at = datetime.now()

    return


a = Foo()

b = Foo()

c = Foo()

d = Foo()


慕雪6442864
浏览 148回答 3
3回答

慕哥6287543

您可以使用类变量来跟踪创建的实例数:class NoteBlock:&nbsp; &nbsp; instance_count = 0&nbsp; # <== Note strange placement:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; #&nbsp; &nbsp; &nbsp;it's a class variable (also&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; #&nbsp; &nbsp; &nbsp;called "class attribute")&nbsp; &nbsp; def __init__(self):&nbsp; &nbsp; &nbsp; &nbsp; NoteBlock.instance_count += 1&nbsp; &nbsp;# <== Note class namespace (NoteBlock)&nbsp; &nbsp; &nbsp; &nbsp; self.instance_number = NoteBlock.instance_count&nbsp; &nbsp; def __str__(self):&nbsp; &nbsp; &nbsp; &nbsp; return str(self.instance_number)note1 = NoteBlock()note2 = NoteBlock()note3 = NoteBlock()note4 = NoteBlock()# ...and for good measure, assign note2 another instance#note2 = NoteBlock()print(note1)print(note2)print(note3)print(note4)输出:1534

梦里花落0921

对象不会自动保存实例化时间;为此,您必须添加一个属性并在__init__当时保存(如您所示)。但是,如果您不喜欢创建对象本身的属性,您也可以在外部按顺序包含对象的数据结构,例如一个简单的列表:foos = []foos.append(Foo())...foos.append(Foo())...foos.append(Foo())...foos[0] #the first createdfoos[1] #the secondfoos[2] #the third

犯罪嫌疑人X

我想扩展 Hkoof 提供的类变量解决方案,通过添加对实例的直接引用,这也有助于保持类一致的实例列表,允许访问上一个/下一个创建的实例。唯一的问题(实际上,其他解决方案也没有涵盖)是实例的删除需要显式的方法调用,这是del不够的:__del__仅在没有对对象的引用时才调用。由于显然无法知道用户/程序员是否保留了对它的任何引用,因此我们需要一种明确的方法来做到这一点;它不能确保实例将被垃圾收集,因为只有在没有对它的引用时才会发生这种情况。class NoteBlock(object):&nbsp; &nbsp; instancies = []&nbsp; &nbsp; def __init__(self, id):&nbsp; &nbsp; &nbsp; &nbsp; self.id = id&nbsp; &nbsp; def __new__(cls, *args, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; instancy = object.__new__(cls)&nbsp; &nbsp; &nbsp; &nbsp; cls.instancies.append(instancy)&nbsp; &nbsp; &nbsp; &nbsp; return instancy&nbsp; &nbsp; def delete(self):&nbsp; &nbsp; &nbsp; &nbsp; self.instancies.remove(self)&nbsp; &nbsp; # the following property methods are only useful for "browsing" between the&nbsp; &nbsp; # instance list&nbsp; &nbsp; @property&nbsp; &nbsp; def previous(self):&nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # "-1" index returns the last object in the instancies list, we&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # don't want that...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; previous_index = self.instancies.index(self) - 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; assert previous_index >= 0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return self.instancies[previous_index]&nbsp; &nbsp; &nbsp; &nbsp; except:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; @property&nbsp; &nbsp; def next(self):&nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return self.instancies[self.instancies.index(self) + 1]&nbsp; &nbsp; &nbsp; &nbsp; except:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return# create some random objectsfrom random import randrangescope_instance_list = []print('Creating instancies:')for i in range(8):&nbsp; &nbsp; index = randrange(100)&nbsp; &nbsp; block = NoteBlock(index)&nbsp; &nbsp; scope_instance_list.append(block)&nbsp; &nbsp; print('\t{} - Block {} created'.format(i + 1, index))# remove a single instancetoRemoveIndex = randrange(8)toRemove = scope_instance_list.pop(toRemoveIndex)print('\nRemoving instance n. {} ({})...'.format(toRemoveIndex + 1, format(toRemove.id)))# we can't use "del", as the __del__ magic method only works as soon as there is# *no* reference left for the object: since we're keeping the "instancies" list# it will never be called, then we need to use an "internal" way to do that;# keep in mind that if you have *any* reference to that object, it will never be# garbage collected until it's "released".toRemove.delete()print('Done!\n')# show the current instance list, including previous and next instancies,# according to the existing objectsprint('Remaining instance list (class instance based):')for i, inst in enumerate(block.instancies):&nbsp; &nbsp; print('\t{} - Block {}: previous: {}, next: {}'.format(&nbsp; &nbsp; &nbsp; &nbsp; i + 1,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; inst.id,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; inst.previous.id if inst.previous else None,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; inst.next.id if inst.next else None))示例输出:Creating instancies:&nbsp; &nbsp; 1 - Block 10 created&nbsp; &nbsp; 2 - Block 23 created&nbsp; &nbsp; 3 - Block 4 created&nbsp; &nbsp; 4 - Block 28 created&nbsp; &nbsp; 5 - Block 9 created&nbsp; &nbsp; 6 - Block 67 created&nbsp; &nbsp; 7 - Block 70 created&nbsp; &nbsp; 8 - Block 73 createdRemoving instance n. 5 (9)...Done!Remaining instance list (class instance based):&nbsp; &nbsp; 1 - Block 10: previous: None, next: 23&nbsp; &nbsp; 2 - Block 23: previous: 10, next: 4&nbsp; &nbsp; 3 - Block 4: previous: 23, next: 28&nbsp; &nbsp; 4 - Block 28: previous: 4, next: 67&nbsp; &nbsp; 5 - Block 67: previous: 28, next: 70&nbsp; &nbsp; 6 - Block 70: previous: 67, next: 73&nbsp; &nbsp; 7 - Block 73: previous: 70, next: None
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python