当你在列表上调用`append`时会发生什么? [英] What happens when you call `append` on a list?
问题描述
首先,我不知道这个问题最合适的标题是什么。 Contender:如何在自定义类中实现 list.append
。
我有一个 class
调用 Individual
。这是类的相关部分:
从itertools导入计数
类个人:
ID = count ()
def __init __(self,chromosomes):
self.chromosomes = list(chromosomes)
self.id = self.ID.next()
这里是我想要做的这个类:
假设我实例化一个新的个体没有染色体: indiv = Individual([])
,我想在以后添加一个染色体到这个人。目前,我必须做:
indiv.chromosomes.append(makeChromosome(params))
<相反,我最想做的是:
<$ p $ p> indiv.append(makeChromosome(params))
。
所以我的问题是:当我在列表上调用 append
时,发生了什么?是否有被调用的 __ append __
(或 __ foo __
)?在我的个人
类中实现这个函数会给我想要的行为吗?
我知道例如,实现 __包含
中的__
以启用如果foo in indiv
的值。如何启用 indiv.append(...)
功能?
.append()
只是一个接受一个参数的方法,你可以很容易地自己定义:
def append(self,newitem):
self.chromosomes.append(newitem)
Firstly, I don't know what the most appropriate title for this question would be. Contender: "how to implement list.append
in custom class".
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:
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))
Instead, what I would ideally like to do is:
indiv.append(makeChromosome(params))
with the same effect.
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?
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()
is simply a method that takes one argument, and you can easily define one yourself:
def append(self, newitem):
self.chromosomes.append(newitem)
No magic methods required.
这篇关于当你在列表上调用`append`时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!