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

喜欢而已 提交于 2019-12-11 03:46:50

问题


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:


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



来源:https://stackoverflow.com/questions/12921222/what-happens-when-you-call-append-on-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!