UserDict Normal methods explanation
I'm reading 'Dive into Python' and the example below gives an explanation for each line but I'm still having trouble interpreting the meaning. Can someone shed some more light on number 1 and 2. I don't understand #1 when it starts stating about the basic technique of this wrapper class...etc... #2 I don't understand it at all. Please assist and educate please.
Example 5.10. UserDict Normal Methods
def clear(self): self.data.clear() ❶
def copy(self): ❷
if self.__class__ is UserDict: ❸
return UserDict(self.data)
import copy ❹
return copy.copy(self)
def keys(self): return self.data.keys() ❺
def items(self): return self.data.items()
def values(self): return self.data.values()
❶ clear is a normal class method; it is publicly available to be called by anyone at any time. Notice that clear, like all class methods, has self as its first argument. (Remember that you don't include self when you call the method; it's something that Python adds for you.) Also note the basic technique of this wrapper class: store a real dictionary (data) as a data attribute, define all the methods that a real dictionary has, and have each class met开发者_如何学Gohod redirect to the corresponding method on the real dictionary. (In case you'd forgotten, a dictionary's clear method deletes all of its keys and their associated values.) ❷ The copy method of a real dictionary returns a new dictionary that is an exact duplicate of the original (all the same key-value pairs). But UserDict can't simply redirect to self.data.copy, because that method returns a real dictionary, and what you want is to return a new instance that is the same class as self.
As for point 1. It just recalls the basics of a wrapper class... IMHO the documentation-block of the clear-method is not really the best place for recalling these basics....
As for point 2. When calling the copy-method of your object you aim to copy your instance, and not the datastore inside the instance ('self.data' in the example above)
self.data.copy copies the datastore: You still do not have a copy of your UserDict instance...
But I wonder if there is not an error in the code extract: "return UserDict(self.data)" --> This would create a new instance on the SAME datastore?! If I am not wrong, it would be correct to call "return UserDict(self.data.copy())" ....
精彩评论