Python note (7): dictionary, class, attribute, object instance, inheritance, python instance
(1) Brief Description
A dictionary is a Python built-in data structure that associates data with keys (for example, name: Zhang San, name is a key, and name is data ). For example, the following is a dictionary.
{'Name': 'zhang san', 'birthdate ': '2017-08-12', 'score ': ['3. 21', '3. 10', '3. 01 ']}
The following describes how to create, add, and access Dictionary data:
D = {}#Create a dictionary directly {}
F = dict ()#Create a dictionary using the factory function dict ()
# Use the following method to add data
D ['Name'] ='Zhang san'
D ['Birthdate'] ='2017-08-12'
D ['Score'] = ['3. 21','3. 10','3. 01','2. 45','2. 34','2. 22','2. 01']
Print (d)
#Access Dictionary data through keys
Print (d ['Name'])
Print (d ['Birthdate'])
Print (d ['Score'])
Print (d ['Score'] [2])
The output is as follows:
(2) convert the list to a dictionary
(1) create a file
James2.txt: name, birth date, and score
James Lee, 2002-3-14,2-34,3: 21, 2.34, 2.45, 3.01, 2-2.01-01
(2) Requirements
Output the following format dictionary on the screen
{'Name': 'James Lee ', 'birthdate': '2017-3-14 ', 'score': ['3. 21', '3. 10', '3. 01 ']}
(3) Main program code
FromFirstPythonImportThe_dictAsTd
The_james2 = td. chdict ('F: \ PythonFile \ james2.txt')
Print (the_james2)
(4) the_dict module code
DefSanitize (time_str ):
#Input a string, modify '-' and ':' To '.', and return the result. Otherwise, return the result directly.
If'-'InTime_str:
(X, y) = time_str.split ('-', 1)
Return(X +"."+ Y)
Elif':'InTime_str:
(X, y) = time_str.split (':', 1)
Return(X +"."+ Y)
Else:
Return(Time_str)
DefChdict (the_file ):
#Input File and return a dictionary
D = dict ()
WithOpen (the_file)AsJames_file:
The_list = james_file.readline (). strip (). split (',')
#Split data and return a list
D ['Name'] = The_list.pop (0)
# Pop ()Delete data items at the specified position and return
D ['Birthdate'] = The_list.pop (0)
D ['Score'] = Sorted (set ([sanitize (t)ForTInThe_list]), reverse =True) [0: 3]
# Set ()Deletes duplicate data and returns an unordered set, sorted by sorted ().
ReturnD
(3) class, attribute, and object instance
Simply put, classes and attributes are abstract concepts, and object instances are a specific "exist ". For example:
Class: person
Attributes: name, height, and weight
Object instances: James and James
People refer to a type of things. Height, name, and weight all have attributes. Zhang San and Li Si refer to a specific person.
(4) creating classes and object instances
class People:
def __init__(self):
Note: The above part is mandatory, where People is the class name and custom, __init _ (self) method controls how to initialize the object, self is also mandatory (this is a target identifier that identifies the current object)
For example:
(1) create a class
ClassPeople:
Def_ Init _ (self, name, date =None, Achievement = []):
# Date, Which has the default value (default) for achievement.
Self. name = name
Self. date = date
Self. achievement = achievement
(2) create an object instance
Zs = People ('Zhang san')
#Create an object instance named zhangsan
Note: Use zs = People ('Zhang san'), It will automatically call the _ init _ () method of the people class, where self = zs, name = 'zhang san', and then create a name = 'zhang san' date =None, Achievement = [] object instance zs
(3) many methods can be defined in the class, but the first parameter of each method must be self (if this parameter is not set, the first parameter will be treated as the self parameter ).
For example:
def chdict(self,the_file):
with open(the_file) as new_file:
the_list = new_file.readline().strip().split(',')
return People(the_list.pop(0),the_list.pop(0),the_list)
def top3(self):
return(sorted(set(self.sanitize(t) for t in self.achievement),reverse=True)[0:3])
(5) Inheritance
You can create a new class from scratch, inherit the created class, and add attributes and methods on this basis.
The concept of inheritance: inherits all methods and attributes of the parent class. You can add methods, attributes, or override methods of the parent class. Simply put, for example, if you inherit all your father's abilities and talents (including height and weight), then you can learn to master more abilities, you can also change the ability to inherit from your father according to your own needs (for example, your father may be used in business negotiation, and you may want to use it on a girl ). The metaphor may not be quite an image. Please forgive me.
(1) create a class through inheritance
ClassPeopleList (list ):
Def_ Init _ (self ):
List. _ init _ ([])
The new PeopleList (list) class will be derived from the list class, and the list. _ init _ ([]) class will be initialized.
(2) For example, the following class can inherit all the methods of list.
class PeopleList(list):
def __init__(self,name,date=None,achievement=[]):
list.__init__([])
self.name = name
self.date = date
self.extend(achievement)
You can test in the Editor:
james = PeopleList('james')
james.append(5)
print(james)
james.extend([1,2,3])
print(james)