Why isn't this infinite recursion?
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
.
精彩评论