小编Thi*_*kid的帖子

Python特殊方法(即魔术方法)__len__什么时候会被调用?

我正在尝试为链接列表创建一个链接列表节点类,如代码所示:

class LNode:
    def __init__(self, data=None, pnext=None):
        self.data = data
        self.pnext = pnext

    def __str__(self):
        return f"{self.data} -> {self.pnext}"

    def __repr__(self):
        return f"{self.data} -> {self.pnext}"

    def __len__(self):
        print("len method called...")
        cnt = 1
        return cnt

    def headInsert(self, nextNode):
        nextNode.pnext = self.pnext
        self.pnext = nextNode

    def headInsert_woh(self, nextNode):
        nextNode.pnext = self
        return nextNode

    def tailInsert(self, nextNode):
        print("tail-insert called...")
        tail = self
        while tail.pnext:
            tail = tail.pnext
        tail.pnext = nextNode
        return self

    def __add__(self, other):
        return self.tailInsert(other)
Run Code Online (Sandbox Code Playgroud)

定义后,我尝试了以下代码:

a = LNode(1)
for …
Run Code Online (Sandbox Code Playgroud)

python magic-methods

4
推荐指数
1
解决办法
240
查看次数

标签 统计

magic-methods ×1

python ×1