I’m currently looking through the “Dive Into Python” to pick up the language and I was a bit confused about chapter 5’s example 5.10. UserDict Normal Methods
Example 5.10. UserDict Normal Methods
def copy(self):
if self.__class__ is UserDict:
return UserDict(self.data)
import copy
return copy.copy(self)
where data is a dictionary.
I notice that if the class is a UserDict type, then it returns UserDict(self.data). What I’m confused about is, why do you need to return UserDict(self.data) instead of just returning self.data? Isn’t self.data a dictionary which you can return?
If someone can explain the difference between returning UserDict(self.data) and self.data, I would appreciate it greatly.
In order to yield a copy, you should use
UserDict(self.data).Why we use
UserDict(self.data)instead of self.data is that it returns new instance which is same class with self.If you return only
self.datathen you didn’t make a copy. Because it returns adict, not an instance ofUserDict. If you want to produce a copy, you should useUserDict(self.data).