Python Learning Notes

Source: Internet
Author: User
Tags set set

Tag: The value at the beginning of the specified ASSM format for statement date Var

1.Python of built-in data structures

(1) List

Create: Created with a pair of curly braces, the element can be any type, for example: list={"Xiaozhang", 1001}, or it can be created from the built-in function list

Access: accessed through the following table, for example, print list[0] results are: Xiaozhang, the list of elements can also be a list, called a two-dimensional list, access to the same as the two-dimensional array

can also be accessed by slicing, such as list[0:1]

Modified: Mode one: list[0]= ' 1 '; This will change the Xiaozhang to 1. Mode Two: Can modify multiple list[0:1]=[1,2 at once]

Delete: 1) through the Remove () function, the parameter is the value to be deleted

2) Delete the value of the specified index in the list by using the Del () function.

(2) tuples, implemented by the built-in function tuple () or created with a pair (), tuples are immutable sequence types, so only access, no deletions and additions, access methods are similar to the list, and are also sliced by way.

(3) A dictionary is a key-value pair that accesses Value,key by key must be a hash type.

Created: 1) Normal mode creation: student={1001: ' Xiaozhang ', 1002: ' Xiaowang '}

2) Dict () function: Studeng=dict ([1001: ' Xiaozhang ', 1002: ' Xiaowang ']), the function parameter is a list or tuple of the form of a key-value pair.

Visit: 1) Specify the way the key is:

"By the way you specify the key (2.2 ago)"
In Student.keys ():
"Student[%s]="%key, Student[key];
"By specified means (after 2.2)"
In student:
"student[%s]="% key, Student[key];

2) via the items () function

' Built-in functions items '
For (Key, instudent.items ():
' student[%s]= '% key,values

3) by Function Iteritems (), using the same 2) function, only this function returns an iterator, (2) returns a tuple

With the new dictionary:

1) Add element: can be implemented by an assignment statement: Dictionary[key]=value, for example: student[1001]= ' Xiaoli '. If key does not exist in the dictionary, the direct element is added to the dictionary, and the value associated with the corresponding key is updated if it exists.

2) Use Dictionary.setdefault (Key,[value]) function to add elements, key is the dictionary keys, value is optional, default is None, if the parameter to add key in the dictionary already exists, then the function will return the original value. Example: Student.setdefault (1004, ' Xiaoliu '), at this time 1004 corresponds to the value of Xiaoliu, again using Student.setdefault (1004, ' Xiaohe '), At this point, value 1004 is not changed to Xiaohe, and is still xiaoliu.

To delete an element:

1) Delete the element in the dictionary via the Del () function, in the syntax format: Del (Dictionary_name[key]), delete the element according to the key value of the dictionary, the deleted element must be present, or throw the Keyerror exception.

2) Delete the elements in the dictionary via the Pop () function, the syntax is: Dictionary_name.pop (Key,[defaultvalue]), the element corresponding to key exists, return value and delete this key value pair, Returns the value of DefaultValue if it does not exist, and does not throw an exception.

(4) Set, set is a set of unordered elements, elements to be hashed objects, types are divided into mutable set set and immutable set Fozenset, often used for member relationship testing and duplicate entry elimination.

Create a collection: 1) Create a mutable collection by using curly braces, each of the elements inside is separated by commas or set (). Creating immutable collections is only possible through Frozenset ().

For example: mutable set: student1_set={' xiaoming ', ' Xiaohua '} student_set=set ([' Xiaoli ', ' xiaoming '])

Immutable collection: Student1_set=frozenset ([' xiaoming ', ' Xiaohua '])

add element: Add an element to the collection by Set.add (), and if you want to add more than one element at a time, you can implement it by Set.update ()

Delete element: 1 removes an element from the collection by removing (obj) or discard (obj), and obj is not an element in the collection, and remove throws a Keyerror exception, discard not thrown.

2) Delete by pop (), delete the first element in the collection and return

3) Clear () Clears all elements in the collection.

Functions in the 2.Python.

1) Define the format

def function name ([parameter list]):

' Document String '

function body

The concept of a null function, defined in the form of

def function name ([parameter list]):

' Document String '

Pass

2) Parameter passing: parameter passing in Python is a reference, called when the argument and formal parameter refer to the same object. But also divided into mutable objects (list dictionary, etc.) and immutable objects (shaping, floating point, strings and tuples, etc.), when the variable object is changed in the function of the parameter parameters will also be modified, the immutable object in the function of the modification does not affect the value of the argument.

3) Variable length parameter: def function name ([positional parameter, default parameter parameter],*vargs_turple). Vargs_turple is a non-keyword variable-length parameter that saves all the parameters that are left after matching the previous positional and default parameters in tuples.  It is generally possible to iterate over a value for a loop. def function name ([positional parameter, default parameter parameter],[*vargs_turple],**vars_dist). **vars_dist is the keyword variable length parameter. It stores the remaining parameters of the previous parameters in a dictionary.

# Coding:utf-8
DefKeywordvarargs (Posarg, defarg=' Defval ', * varargs, * * Kwvargs):
Print' Positional parameter ppsarg: ', Posarg
Print' Default parameter defarg: ', Defarg
For EachvarIn VarArgs:
Print' Non-keyword variable-length parameter: ', Eachvar
For keyIn Kwvargs:
Print' keyword variable length parameter ' +key+‘:‘, Kwvargs[key]
Print "does not specify a keyword variable length parameter: '
Keywordvarargs (123 ' abc ' print "Specifies the keyword variable length parameter: '
Keywordvarargs (123 ABC ' kw1=1< Span style= "COLOR: #cc7832", kw2= ' 333 ')

Output Result:

Do not specify a variable length parameter for the keyword:
Position parameter ppsarg:123
Default parameter Defarg:abc
Non-keyword variable length parameter: 456
Non-keyword variable-length parameter: wer
Specifies the keyword variable length parameter:
Position parameter ppsarg:123
Default parameter Defarg:abc
Non-keyword variable length parameter: 456
Non-keyword variable-length parameter: wer
Keyword variable length parameter kw1:1
Keyword variable length parameter kw2:333
3. Object-Oriented Programming

Python also defines a class from the keyword class, and the usage is basically consistent with Java. But Python also has its own special grammatical rules.

(1) There is no private or public keyword in Python, so to declare a private variable or private method, which is a special conforming representation and begins with two underscores, is a private property. For example, private attribute __manufactueprice=20. Objects that are external to the class. __manufactueprice is not accessible. In fact, it is not really access, but the compiler automatically turn this property name into _car__manufactueprice, by

The object. _car__manufactueprice can still be accessed.

(2) The constructor function in Python is the __init__ (self) function. This method can only be defined once, does not allow overloading, when the definition is multiple, the following will overwrite the previous one. Overloads that want to implement constructors can use the form of default parameters.

ClassCar (Object):
"" "DocString for Car" ""
# def __init__ (self):
# Pass
Def__INIT__ (Self, name=None, model=None, year=None):
Self.__name = name;
Self.__model=model;
Self.__year=year;
Self.__oldmeter=0;
DefSetName (Self, name):
Self.__name=name;
DefSetmodel (Self, model):
Self.__model=model;
DefSetyear (Self, year):
Self.__year=year;
DefSetoldmeter (Self, Oldmeter):
Self.__oldmeter=oldmeter;
DefGet_descriptive_name (Self):
"" "" Return all Descriptive_name "" "
Long_name=StrSelf.__year) +"+StrSelf.__name) +"+StrSelf.__model);
return long_name;
DefRead_oldmeter (Self):
Print"The car has" +StrSelf.__oldmeter) + ' miles on it. ';
def update_oldmeter (self,mileage):
self.__ Oldmeter=mileage;
def increment_oldmeter ( Span style= "COLOR: #94558d" >self,miles):
self.__ Oldmeter+=miles;
def fillgastank (self,gas):
Print "The car has an add" +str (gas) +

Main function:

From ClasstestImport Car, Electriccar
My_new_car = car ()
My_new_car.setname (' Aodi ')
My_new_car.setmodel (' A6 ')
My_new_car.setoldmeter (1000)
My_new_car.setyear (2016)
Print' Car name: '
Print (My_new_car.get_descriptive_name ());
My_new_car.read_oldmeter ();
My_new_car.update_oldmeter (23);
My_new_car.read_oldmeter ();
My_new_car.increment_oldmeter (100);
My_new_car.read_oldmeter ();
My_new_car.fillgastank (220);
Print my_new_car._car__name;
MY_NEW_CAR2 = Car (' Frali ',' 2016 ')
Print ' Car name: '
Print (My_new_car2.get_descriptive_name ());
My_new_car2.read_oldmeter ();
My_new_car2.update_oldmeter (23);
My_new_car2.read_oldmeter ();
My_new_car2.increment_oldmeter (100);
My_new_car2.read_oldmeter ();
My_new_car2.fillgastank (220);
print my_new_car2._car__name;

Output Result:

Car Name:
Aodi A6
The car has a. miles on it.
The car has a miles on it.
The car has 123 miles on it.
The car has an add gas.
Aodi
Car Name:
Frali 23
The car has 0 miles on it.
The car has a miles on it.
The car has 123 miles on it.
The car has an add gas.
Frali

(3) class methods and static methods: A common method can be converted to a class method or a static method through the @classmethod and @staticmethod methods or corresponding built-in functions.

Python Learning Notes

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.