returning data in python
I'm 开发者_StackOverflow社区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.
It returns a new UserDict
object because .copy()
is expected to return an object of the same type its copying.
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.data
then you didn't make a copy. Because it returns a dict
, not an instance of UserDict
. If you want to produce a copy, you should use UserDict(self.data)
.
What you're looking at here is an optimization.
You can use UserDict
as a base class to write your own subclass. If you don't override the copy()
method on your subclass, then you get the one from the base class, i.e., the one you're looking at here.
So basically, it's checking to see if it's running in a subclass. If it's not, it knows that the fastest way to make a copy of itself is to use its own constructor. But if it's running in a subclass, it doesn't know what you might have added and what needs to be copied, so it uses a more generic copy function from the copy
module. This won't be as fast, but it is more likely to copy what needs to be copied. (Of course, you should maybe write your own copy()
method if you subclass UserDict
...)
It doesn't return self.data
because self.data
is a dict
, not a UserDict
, and it's not a copy.
精彩评论