当你在列表上调用 `append` 会发生什么?

当你在列表上调用 `append` 会发生什么?

问题描述:

首先,我不知道这个问题最合适的标题是什么.竞争者:如何在自定义类中实现 list.append".

Firstly, I don't know what the most appropriate title for this question would be. Contender: "how to implement list.append in custom class".

我有一个 class 叫做 Individual.这是课程的相关部分:

I have a class called Individual. Here's the relevant part of the class:

from itertools import count
class Individual:
    ID = count()
    def __init__(self, chromosomes):
        self.chromosomes = list(chromosomes)
        self.id = self.ID.next()

这是我想用这个类做的事情:

Here's what I want to do with this class:

假设我实例化一个没有染色体的新个体:indiv = Individual([]),我想稍后向这个个体添加一条染色体.目前,我必须这样做:

Suppose I instantiate a new individual with no chromosomes: indiv = Individual([]) and I want to add a chromosome to this individual later on. Currently, I'd have to do:

indiv.chromosomes.append(makeChromosome(params))

相反,我最想做的是:

indiv.append(makeChromosome(params))

效果一样.

所以我的问题是:当我在列表上调用 append 时,幕后到底发生了什么?是否有被调用的 __append__(或 __foo__)?在我的 Individual 类中实现那个函数会得到我想要的行为吗?

So my question is this: when I call append on a list, what really happens under the hood? Is there an __append__ (or __foo__) that gets called? Would implementing that function in my Individual class get me the desired behavior?

例如,我知道我可以在 Individual 中实现 __contains__ 以启用 if foo in indiv 功能.我将如何启用 indiv.append(...) 功能?

I know for instance, that I can implement __contains__ in Individual to enable if foo in indiv functionality. How would I go about enable indiv.append(…) functionality?

.append() 只是一个接受一个参数的方法,你可以很容易地自己定义一个:

.append() is simply a method that takes one argument, and you can easily define one yourself:

def append(self, newitem):
    self.chromosomes.append(newitem)

不需要魔法方法.