Python Basics (eight)

Source: Internet
Author: User
Tags date1

Key words: Private variable, class static variable, generator, import Python module, r view module can use function, view Help information, launch external program, collection, heap, Time module, Random module, shelve module, file read etc.

>>> class Rectangle:

... def __init__ (self):

... self.__width = 0

... self.__height = 0

... def setSize (self,width,height):

... self.__width = width

... self.__height = height

... def getsize (self):

... return self. __width,self. __width

...

>>> class Staticvariable:

var = 0 #类静态变量, references need to use Staticvariable.var

... def __init__ (self):

... Staticvariable.var = 10

... def setVar (self,input):

... self.var = input

...

>>> Staticvariable.var

0

>>> s = staticvariable ()

>>> Staticvariable.var

10

>>> S.setvar (100)

>>> Staticvariable.var

10

>>> class Staticmethodtest:

... @staticmethod

... def smeth ():

... print ("This is a static method")

... @classmethod

... def cmethod (CLS):

... print ("This is a class method")

...

>>> staticmethodtest (). Smeth ()

This is a static method

>>> staticmethodtest (). Cmethod ()

This is a class method

The function that contains the yield statement becomes the generator, which outputs the results uniformly over multiple times.

>>> def flatten (nested):

... for sublist in nested:

... for element in sublist:

... yield element

...

>>> nested = [[1,2],[3,4],[5]]

>>> list (Flatten (nested))

[1, 2, 3, 4, 5]

Recursive use builder

>>> def flatten (nested):

... try:

... for sublist in nested:

... for element in flatten (sublist):

... yield element

... except TypeError:

... yield nested

...

>>> nested = [[1,2],[3],[4,5]]

>>> list (Flatten (nested))

[1, 2, 3, 4, 5]

>>> nested = [[[1],2],3,[4,5]]

>>> list (Flatten (nested))

[1, 2, 3, 4, 5]

To import a Python module from another location, assume that there is a testpython.py file under the C:\python directory, which reads as follows:

def addfunction (ARG1,ARG2):

return int (arg1) + int (arg2);

The following methods are available when you need to use the module:

>>> Import Sys

>>> sys.path.append ("C:/python")

>>> Import Test

>>> Import Testpython

>>> testpython.addfunction (3,4)

7

>>> from Testpython import addfunction as add

>>> Add (8,9)

17

After introducing testpython.py, the __pycache__ folder should be generated in the C:\python directory.

So we usually write our own programs. It is best to add your own module path to the current module scan path, Eg:sys.path.append (' Your module's name '), so that the program will not be unable to find the module and error

>>> Import Sys

>>> Sys.path

You can see the path the Python program is looking for when it executes. The Site-packages directory is the best choice, just put the module in the site-packages corresponding directory, all programs can refer to the module.

Assuming that there is a module named drawline.py under the C:\python\packagetest directory, you can import the module as follows:

>>> Import Packagetest.drawline

Drawing a line!

Special variables in Java that begin with the underscore

_xxx, similar to protect in Java, can only be accessed by the class itself and its subclasses. cannot be imported with ' from module import * '.

The __XXX__ system-defined name, such as x = new DrawLine (), calls DrawLine's __init () __ function.

The private variable name in the __xxx class, which can only be accessed by the class itself.

Use Dir to view the functions that the module can use without underlining the beginning

>>> Import Copy

>>> [n for N with dir (copy) if not N.startswith ("_")]

[' Error ', ' pystringmap ', ' builtins ', ' Copy ', ' deepcopy ', ' dispatch_table ', ' Erro

R ', ' name ', ' t ', ' weakref ']

__all__ explains that the from copy import * Only imports these three functions, and that using other functions requires an explicit import.

>>> copy.__all__

[' Error ', ' Copy ', ' Deepcopy ']

__all__ is useful when writing a module, and other programs do not need or want to be referenced to use __all__ filtering. These functions are not imported when you use import *.

View more detailed Help information

>>> Import Copy

>>> Help (copy)

Or

>>> copy.__doc__

View the source code for a module file

>>> copy.__file__

' F:\\java Learning materials \\python\\pythonexe\\lib\\copy.py '

ARGV is the command-line argument, Argv[0] is the name of the script.

#reverseargs. py

Import Sys

args = sys.argv[1:]

Args.reverse ()

Print ("". Join (args))

You can test on the command line:

F:\JAVA Learning Materials \python\pythonexe>reverseargs.py This is a test

Testaisthis

View environment variables

>>> Print (Os.environ)

File delimiter

>>> Print (OS.SEP)

\

Os.system ("") is used to start external programs, and some functions can execute external programs. For example, Execv quits the Python interpreter and gives control to the executing program. There are also popen that can create a class file that connects to the program.

>>> Import OS

>>> os.system ("cmd")

Microsoft Windows XP [version 5.1.2600]

(C) Copyright 1985-2001 Microsoft Corp.

F:\JAVA Study Materials \python\pythonexe>

You can use the following command to open IE browser, it is important to note that there are spaces in the path before and after the need to add a grid, or DOS in the resolution of the error.

>>> Os.system (r ' C \ n "program Files" \ "Internet Explorer" \iexplore.exe ')

There is one more way to do this:

>>> os.startfile ("C:\Program files\internet Explorer\iexplore.exe")

In addition to lists, tuples, dictionaries, there are several more commonly used data structures: collections, heaps, and double-ended queues.

>>> Set (range (10))

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

It can be seen that the dictionary is not the same as the dictionary format {"name": "Alice", "Age": "17"}

The way to build the collection is also less consistent with the build list, which is generated for the list:

[x for X in range (10)]

There are no duplicate elements in the collection, which are primarily used to check membership:

>>> set ([1,2,2,3,4,5,5])

{1, 2, 3, 4, 5}

In addition to checking the membership, the collection can be easily performed with the set and the difference set:

>>> a = set ([[+])

>>> B = Set ([2,3,4])

>>> A.union (b)

{1, 2, 3, 4}

>>> A-B

{1}

>>> A & B

{2, 3}

>>> a = []

>>> for I in range (10):

... a.append (set (range (i,i+5)))

...

>>> A

[{0, 1, 2, 3, 4}, {1, 2, 3, 4, 5}, {2, 3, 4, 5, 6}, {3, 4, 5, 6, 7}, {8, 4, 5, 6

, 7}, {8, 9, 5, 6, 7}, {8, 9, 10, 6, 7}, {8, 9, 10, 11, 7}, {8, 9, 10, 11, 12},

{9, 10, 11, 12, 13}]

>>> s = set ()

>>> for SEG in a:

... s = s.union (SEG)

...

>>> s

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}

>>> dict (name = "Alice", Age =17)

{' name ': ' Alice ', ' Age ': 17}

The set is mutable and cannot be used as a key for a dictionary like a tuple, but Frozenset represents an immutable collection that can be used for the keys of a dictionary.

Python does not have a heap of this type, only the HEAPQ module has several operations on the heap.

Heappush to add new elements to the heap.

>>> from HEAPQ Import *

>>> heap = [x for x in range (10)]

>>> Heappush (heap,0.5)

>>> Heap

[0, 0.5, 2, 3, 1, 5, 6, 7, 8, 9, 4]

Heappop operation, the smallest element in the pop-up heap.

>>> Heappop (Heap)

0

>>> Heap

[0.5, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Heapreplace the smallest element in the heap and joins the new element to the heap.

>>> Heapreplace (heap,0.2)

0.5

>>> Heap

[0.2, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Nlargest returns the largest n elements in a heap.

>>> Nlargest (3,HEAP)

[9, 8, 7]

[x for X in Dir (collections) if not X.startswith ("_")]

The deque,2 side of the double-ended queue can be added to the queue to delete operations.

>>> from collections Import deque

>>> q = deque (range (5))

>>> Q

Deque ([0, 1, 2, 3, 4])

>>> Q.append (5)

>>> Q.appendleft (6)

>>> Q

Deque ([6, 0, 1, 2, 3, 4, 5])

>>> Q.pop ()

5

>>> Q

Deque ([6, 0, 1, 2, 3, 4])

>>> Q.popleft ()

6

>>> Q

Deque ([0, 1, 2, 3, 4])

>>> Q.rotate (3)

>>> Q

Deque ([2, 3, 4, 0, 1])

The time module contains operations that are related to processing times.

>>> Import Time

>>> Time.asctime ()

' Fri 15 14:47:10 2014 '

>>> [n for N with dir (time) if not N.startswith ("_")]

[' Altzone ', ' asctime ', ' clock ', ' ctime ', ' Daylight ', ' get_clock_info ', ' gmtime ',

' LocalTime ', ' mktime ', ' monotonic ', ' perf_counter ', ' process_time ', ' sleep ', ' s

Trftime ', ' strptime ', ' struct_time ', ' time ', ' timezone ', ' tzname '

>>> Time.gmtime ()

Time.struct_time (tm_year=2014, tm_mon=8, tm_mday=15, tm_hour=6, tm_min=48, Tm_se

C=34, tm_wday=4, tm_yday=227, tm_isdst=0)

>>> Time.time ()

1408085392.830139

>>> Time.localtime ()

Time.struct_time (tm_year=2014, tm_mon=8, tm_mday=15, tm_hour=14, tm_min=50, tm_s

ec=49, tm_wday=4, tm_yday=227, tm_isdst=0)

Operations that are related to generating random numbers can use the random module

>>> from random Import *

>>> Random ()

0.5195714588052318

>>> Uniform (2,6) #将返回介于a和b之间的一个数

2.096032872509754

>>> Randrange (2,6,1) #第三个参数表示步长

5

>>> Choice (["Alice", "Anna", "Altria"]) #返回随机的元素

' Anna '

>>> sample (["Alice", "Anna", "Altria", "Anna", "Alice"],2) #返回n个不重复的随机元素

[' Altria ', ' Anna ']

Time class in-depth understanding

(2008,1,1,0,0,0,-1,-1,-1)

The meanings of each position are explained in the order of location:

Years, months, days, hours, minutes, seconds, Weeks, Confucianism calendar day, daylight saving time.

>>> from random Import *

>>> From time Import *

>>> date1 = (2008,1,1,0,0,0,-1,-1,-1)

>>> date2 = (2009,1,1,0,0,0,-1,-1,-1)

>>> time1 = mktime (date1)

>>> time2 = mktime (date2)

>>> random_time = uniform (time1,time2)

>>> Print (localtime (random_time))

Time.struct_time (tm_year=2008, tm_mon=3, tm_mday=10, tm_hour=10, tm_min=23, tm_s

Ec=55, Tm_wday=0, tm_yday=70, tm_isdst=0)

>>> Print (Asctime (localtime (random_time)))

Mon Mar 10 10:23:55 2008

The shelve module can use Python's default storage, store data in a specified file name, use the open method to read data from a file, and modify the data to write changes to disk using the Close method.

>>> Import Shelve

>>> s = Shelve.open ("Test.dat")

>>> s[' x '] = ["A", "B", "C", "D"]

>>> s["x"].append ("D")

>>> s["x"]

[' A ', ' B ', ' C ', ' d ']

>>> S.close ()

Test data is written to disk

>>> Import Shelve

>>> s = Shelve.open ("Test.dat")

>>> s["x"]

[' A ', ' B ', ' C ', ' d ']

The Test.dat file can be found under the Pyhon installation directory.

The data in the file that the shelve module operates in is also the form of a key-value pair, which differs from the dictionary in that the data in the dictionary is not stored on the hard disk, is lost after a reboot, and shelve writes data to the hard disk.

The RE module provides support for regular expressions.

Operations on files

>>> f =open ("Some.txt", "W")

>>> f.write ("Hello,")

6

>>> F.write ("World")

5

>>> F.close ()

A newly created file named Some.txt can be found under the installation path of Python.

Operations to read files:

>>> file = open (r "F:\python\pythonexe\some.txt")

The meaning of the second parameter in F =open ("Some.txt", "W"):

W-write mode, R-read mode, +-read/write mode, a-append mode, B-binary mode

If the file being processed is a binary file, such as a sound, the video file needs to use the B parameter, and if it just reads a binary file, the second parameter can use the RB parameter.

The third parameter of the Open function controls caching, which means that memory is used instead of the hard disk for file reads, the program is faster, and flush or close is used to write data from the cache to the hard disk.

When the third parameter of the Open function is 0 to indicate that the cache is not used, a negative number indicates that the default cache is used, and numbers greater than 1 indicate the size of the cache in bytes.

>>> f = open ("Some.txt", "R")

>>> F.read (4) #参数表示的是将要读取的字节数

' Hell '

>>> F.read ()

' O,world '

ReadLine and Writelines can read or write a line of characters.

Write and Writelines will overwrite the original content in the file by default.

Need to use Append mode, f = open ("Some.txt", "a")

Python's operation of the file should finally be closed, such as writing to the file, the modification may still be in the cache when the program crashes, and if you do not write, the changes will be completely lost.

The closing of the file should be done in the finally:

Try

f = open ("Some.txt", "R")

#else Code

Finally

F.close ()

Some notes about line breaks do not need to be escaped again, otherwise they cannot be wrapped.

>>> f= Open ("Some.txt", "a")

>>> f.write ("Append line \ n")

You can see that the file stream in Python was last read as an empty string, not 1 in Java

>>> def fun (f):

... while True:

.... Char = F.read (1)

... if not char:

... print (char, "is the End")

... break

...

>>> f= Open ("Some.txt", "R")

>>> Fun (f)

Is the end

None, "," "," "" "" "," ", (), [],{},0,0.0,0l,0j are all false

Cycle through each character

>>> f= Open ("Some.txt", "R

>>> while (True):

.... Char = F.read (1)

... if not char:break

.. else:

... print (char)

>>>f.close ()

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.