Vi. Customizing Data Objects (object-oriented python)-----packaging code and data

Source: Internet
Author: User

    • Create a Python dictionary

The Python dictionary is a key-value pair, equivalent to a map in Java, which is created in two forms:

A = {}     #  normal way B = dict ()  #  using Factory functions
    • Assignment and access of dictionaries
#Create a dictionary>>> cleese['Name'] ='John Cleese'>>> cleese['Occupations'] = ['actor','comedian','writer','film producer']>>> Palin = {'Name':'Michael Palin','Occupations':['comedian','actor','writer','TV']}#Access>>>palin['Name'] 'Michel Palin'>>>cleese['Occupations'][-1]#use numbers to access list items stored in a specific dictionary key location. This can be thought of as ' index chain ', right-to-left reading: "... The last item of the list associated with occupations ... "
    • On the dictionary, the point is that it maintains the association, not the order!
    • Object-oriented python: Define a class
class Athlete:                        #There is no new keyword in python, you can use the __init__ () method to customize the initialization state of an object    def__init__ (self):         # the code to initialize the object is put here  = athlete ()   # Creating an object instance
    • The importance of the self parameter in the init () method

When dealing with a = athlete () This line of code, Python translates to the following call: Athlete (). __init__ (a), at which point a corresponds to self in the __init__ (self), The Python interpreter now knows which object instance the method invocation will be applied to.

    • The first argument of each method is self

Python requires that the first argument of each method be the calling object instance, that the first argument of each method must be self

Example code:

classAthlete:def __init__(self,a_name,a_dob=none,a_times=[]): Self.name=a_name Self.dob=A_dob self.times=A_timesdefTOP3 (self):#The 5th chapter of the last question, return 3 the fastest time, don't forget the self parameter here        return(Sorted (Set ([Sanitize (t) forTinchSelf.times]) [0:3])defGet_coach (filename):Try: with open (filename) as F:data=f.readline () Templ= Data.strip (). Split (',')        return(athlete (templ.pop (0), Templ.pop (0)), Templ)exceptIOError as Ioerr:Print('File Error:'+str (ioerr))return(None) James= Get_coach_data ('James2.txt')Print(James.name +"' s fastest times are:"+ str (JAMES.TOP3 ()))#Call the TOP3 () method to convert the result to a string before displaying the result on the screen
    • Inherit Python's built-in list---How to inherit Python's built-in classes
class Namedlist (list):       # creates a namedlist class, and the new class inherits the list class    def__init__(self,a _name):        list. __init__ ([])    # initializes the derived class and assigns the parameter to the property        self.name = a_name

This allows the namedlist to use the list's built-in methods such as Namedlist (). Append ("xxx")

Vi. Customizing Data Objects (object-oriented python)-----packaging code and data

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.