What happens when you call `append` on a list?

2019-07-17 00:43发布

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?

1条回答
淡お忘
2楼-- · 2019-07-17 01:12

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

查看更多
登录 后发表回答