开发者

Why isn't this infinite recursion?

开发者 https://www.devze.com 2023-02-17 21:34 出处:网络
I would like to ask you about a code in P开发者_开发问答ython: class UserDict: def __init__(self, dict=None, **kwargs):

I would like to ask you about a code in P开发者_开发问答ython:

class UserDict:
    def __init__(self, dict=None, **kwargs):
        self.data = {}
        if dict is not None:
            self.update(dict)
        if len(kwargs):
            self.update(kwargs)
    def clear(self): self.data.clear()

Here, clear(self) is a method of UserDict class, and operates on class's data attribute, right? Won't this function operate on data forever? Because it calls itself every time?


UserDict.clear() calls self.data.clear(). self.data is of type dict, not UserDict, so it calls a different method, not itself. It would be an infinite recursion if UserDict.clear() called self.clear() instead of self.data.clear().


No, This method calls the clear method of the data dict, which is totally unrelated to UserDict.

0

精彩评论

暂无评论...
验证码 换一张
取 消