Python fragmentation knowledge (8): UserDict class

Source: Internet
Author: User

I. UserDict Overview
The UserDict class in the UserDict module is frequently used in python and is stored in UserDict. py under the lib directory of the Python installation directory. Its Dictionary is displayed as follows:

 1 ""A more or less complete user-defined wrapper around dictionary objects.""" 2  3 class UserDict:                    [1] 4     def __init__(self, dict=None, **kwargs):   [2] 5         self.data = {}                [3] 6         if dict is not None:             [4] 7             self.update(dict)            [5] 8         if len(kwargs): 9             self.update(kwargs)10     def __repr__(self): return repr(self.data)11     def __cmp__(self, dict):12         if isinstance(dict, UserDict):13             return cmp(self.data, dict.data)14         else:15             return cmp(self.data, dict)16     def __len__(self): return len(self.data)

.......... Omitted

Note:
[1].UserDictIs a base class, not inherited from any other class
[2 ].DictInput a dictionary in the parameter to define the initial value.
[3]. Python supports data attributes. The preceding data (in C # And C ++, is called a data member, and in java, is called an instance variable ). It is the data owned by a specific class instance. In this exampleUserDictThe instance will haveDataData attributes.
Reference: (1) to reference this attribute from code outside the class, you need to limit it with the instance name,Instance. Data, The method of limitation is the same as that of using the module name to limit the function.
(2) To reference a data attribute inside the class, we useSelfAs a qualifier

Traditionally, all data attributes are_ Init __Method is initialized as a meaningful value. However, this is not necessary, because data attributes, like local variables, are generated when you grant them a value for the first time.
[4]. if... is... syntax
[5].UpdateThe method is a dictionary replicaset: It copies all the keys and values in a dictionary to another dictionary. This operationNoClear the target dictionary in advance. If some keys already exist in the target dictionary, they will be overwritten, and those keys that do not exist in the target dictionary will not be changed. You shouldUpdateIt is regarded as a merging function, rather than a copying function.

II,UserDictGeneral Method

 1 def clear(self):                        #[1] 2     self.data.clear()                   #[2] 3 def copy(self):                         #[3] 4     if self.__class__ is UserDict:     #[4] 5         return UserDict(self.data) 6     import copy 7     return copy.copy(self)             #[5] 8 def keys(self): 9     self.data.keys()10 def items(self):11     self.data.items()12 def values(self):13     self.data.values()

Note: Basic encapsulation technology:
Convert a real Dictionary (Data) Is saved as a data attribute, defines all methods owned by the real dictionary, and redirects each class method to the corresponding method on the real dictionary. (The preceding clear corresponds to the clear () method in dictionary)

1 Delete element from dictionary 2 >>> d 3 {'server': 'mpilgrim', 'uid': 'sa ', 'database': 'master', 42: 'Douglas ', 'retrycount': 3} 4 >>> del d [42] 5 >>> d 6 {'server': 'mpilgrim', 'uid ': 'sa ', 'database': 'master', 'retrycount': 3} 7 >>> d. clear () 8 >>> d 9 10 del allows you to use keys to delete independent elements from a dictionary. 11 clear clears all elements from a dictionary. Note that the empty braces indicate a dictionary with no elements.

 

[1].ClearIs a common class method that can be publicly called by anyone at any time. Note,ClearUseSelfAs its first parameter. (Remember, when you call a method, you do not need to includeSelfThis is something Python has done for you .)

[2]. Real dictionaryCopyThe method returns a new dictionary, which is the original copy of the original dictionary (all key-value pairs are the same ). HoweverUserDictCannot be simply redirectedSelf. data. copyBecause that method returns a real dictionary, and what we want is to return a new instance of the same class, likeSelf.

[3]. We use_ Class __Attribute to check whetherSelfIsUserDictIf yes, it would be great because we know how to copyUserDict: Create a NewUserDictAnd pass it to the real dictionary, which has been stored inSelf. data. Then you immediately return the newUserDictYou don't even need to useImport copy.

[4]. IfSelf. _ class __NoUserDict, ThenSelfYesUserDictA subclassFileInfo), Life is always unexpected.UserDictI don't know how to generate an original copy of its subclass. For example, it is possible to define other data attributes in the subclass, so we can only completely copy them, are you sure you have copied all of them. Fortunately, Python uses a module to perform this task correctly. It is calledCopy. Can copy any Python object.

[5]. Other methods are directly redirectedSelf. dataBuilt-in functions.

Iii. Directly inherit from built-in data typesDict

Note: dict is a built-in data type, which can be used anywhere, just like built-in functions. In python, you can directly inherit from the built-in data type dict, as follows:
1. inherited fromUserDict. UserDict

1 # inherited from UserDict. userDict 2 # import UserDict this error. Be sure to import UserDict class 3 of the UserDict module from UserDict import UserDict4 class FileInfo (UserDict ): 5 "store file metadata" 6 def _ init _ (self, filename = None): 7 UserDict. _ init _ (self) 8 self ["name"] = filename

2. Directly inherit from built-in data typesDict

1 # directly inherit from the built-in data type dict2 class demo (dict): 3 def _ init _ (self, test = None): 4 self ["name"] = test

We found that the second method was much simpler. The differences between them are as follows:

(1) No need to importUserDictModule, becauseDictIs a built-in data type that can be used.
(2) Different inheritance Methods: one is inherited fromUserDict. UserDict, The other directly inherits fromDict
(3)UserDictThe internal work method requires you to manually call it_ Init __Method to correctly initialize its internal data structure.DictIt does not work like this. It is not an encapsulation and therefore does not require Explicit initialization.

Iv. python class depth [1]

1. Reload
In each programming language, there are generally two overload methods:
(1). Through the overload of the parameter list, a class can have multiple methods with the same name, but these methods have different numbers of parameters or different parameter types, such as java
(2 ). supports parameter name overloading. A class can have multiple methods of the same name. These methods have the same type and number of parameters, but their names are different, such as (PL/SQL)

Note: Python is not supported!
In short, there is no function overload in any form. One_ Init __The method is_ Init __Method, regardless of its parameters. Each class can have only one_ Init __Method, and if a subclass has_ Init __Method, it always overwrites the parent class_ Init __Methods, and even subclasses can be defined using different parameter lists. Subclass can override methods in the parent class.

2. About data attributes
Always in_ Init __Method to assign an initial value to all data attributes of an instance. This will save you time for subsequent debugging, and you do not have to capture the cause of uninitialized (or nonexistent) attributes.AttributeErrorException is time-consuming and labor-intensive.

In Java, static variables (class attributes in Python) and instance variables (data attributes in Python) are defined after the class definition.StaticKeyword, none ). In Python, only class attributes can be defined here, and data attributes can be defined in_ Init __Method.

Refer to Dive Into Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.