zoukankan      html  css  js  c++  java
  • Python基础篇(八)

    key words:私有变量,类静态变量,生成器,导入Python模块,r查看模块可以使用的函数,查看帮助信息,启动外部程序,集合,堆,时间模块,random模块,shelve模块,文件读取等

    >>> 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  #类静态变量,引用需要使用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

      含有yield语句的函数成为生成器,会将多次的结果统一的输出。

    >>> 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]

      递归的使用生成器

    >>> 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]

      导入其他位置的Python模块,假设C:python目录下有一个testPython.py的文件,内容如下:

    def AddFunction(arg1,arg2):

        return int(arg1) + int(arg2);

      需要使用该模块时可以使用如下的方法:

    >>> 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

      引入testPython.py后,C:python目录下应该生成__pycache__文件夹。

      所以我们一般自己写程序的话。最好把自己的模块路径给加到当前模块扫描的路径里,eg: sys.path.append('你的模块的名称'),这样程序就不会因为找不到模块而报错

    >>> import sys

    >>> sys.path

      可以查看python程序执行时要查找的路径。site-packages目录是最佳的选择,只需要将模块放入site-packages对应的目录下,所有程序都可以引用该模块。

      假设C:pythonpackagetest目录下有一个名为drawline.py的模块,可以按照如下方式导入模块:

    >>> import packagetest.drawline

    drawing a line!

      Java中以下划线开头的特殊变量

      _xxx ,类似于java中的protect,只能由类自身及子类访问。不能用’from module import *’导入。

      __xxx__ 系统定义名字,如x = new drawline()时会调用drawline的__init()__函数。

      __xxx 类中的私有变量名,只能由类自身访问到。

      使用dir查看模块可以使用的函数,不以下划线开头

    >>> import copy

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

    ['Error', 'PyStringMap', 'builtins', 'copy', 'deepcopy', 'dispatch_table', 'erro

    r', 'name', 't', 'weakref']

      __all__说明了from copy import *只会导入这三个函数,使用其他的函数需要显式的导入。

    >>> copy.__all__

    ['Error', 'copy', 'deepcopy']

      编写模块时__all__是很有用的,其他程序不需要或者不希望被引用的都可以使用__all__过滤。使用import *时不会导入这些函数。

      查看更为详细的帮助信息

    >>> import copy

    >>> help(copy)

    或者

    >>> copy.__doc__

      查看模块文件的源代码

    >>> copy.__file__

    'F:\JAVA学习资料\python\pythonexe\lib\copy.py'

      argv是命令行参数,argv[0]是脚本的名称。

    #reverseargs.py

    import sys

    args = sys.argv[1:]

    args.reverse()

    print("".join(args))

      可以在命令行中进行测试:

    F:JAVA学习资料pythonpythonexe>reverseargs.py this is a test

    testaisthis

      查看环境变量

    >>> print(os.environ)

      文件分隔符

    >>> print(os.sep)

      os.system("")用于启动外部程序,还有一些函数可以执行外部程序。如execv,会退出Python解释器,将控制权交给执行程序。还有popen,可以创建与程序连接的类文件。

    >>> import os

    >>> os.system("cmd")

    Microsoft Windows XP [版本 5.1.2600]

    (C) 版权所有 1985-2001 Microsoft Corp.

    F:JAVA学习资料pythonpythonexe>

      可以用如下的命令打开IE浏览器,需要注意的是路径中有空格的部分前后需要加上空格,否则DOS在解析的时候就会出错。

    >>> os.system(r'C:"Program Files""Internet Explorer"iexplore.exe')

      完成上述功能还有下面的一种方法:

    >>> os.startfile("C:Program FilesInternet Exploreriexplore.exe")

      除了列表,元组,字典,还有下面几种较为常用的数据结构:集合,堆和双端队列。

    >>> set(range(10))

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

      可以看出和字典还是不同的,字典的格式为{“name”:”alice”,”age”:”17”}

      生成集合的方式也和生成列表的不太一致,生成列表的为:

    [x for x in range(10)]

      集合中没有重复的元素,主要用于检查成员资格:

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

    {1, 2, 3, 4, 5}

      除了可以检查成员资格,集合还可以方便地进行并集和差集的操作:

    >>> a = set([1,2,3])

    >>> 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}

      set是可变的,不能像元组一样用于字典的键,但是frozenset表示不可变的集合,可以用于字典的键。

      Python中并没有堆这个类型,只有heapq模块中有若干关于堆的操作。

      heappush操作,将新元素加入到堆中。

    >>> 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操作,弹出堆中最小的元素。

    >>> heappop(heap)

    0

    >>> heap

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

      heapreplace弹出堆中最小的元素,并将新元素加入到堆中。

    >>> heapreplace(heap,0.2)

    0.5

    >>> heap

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

      nlargest返回堆中的最大的n个元素。

    >>> nlargest(3,heap)

    [9, 8, 7]

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

      双端队列deque,2端都可以做添加,删除操作的队列。

    >>> 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])

      time模块包含了处理时间相关的操作。

    >>> import time

    >>> time.asctime()

    'Fri Aug 15 14:47:10 2014'

    >>> [n for n in 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)

      和生成随机数相关的操作可以使用random模块

    >>> 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类深入理解

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

      各位置含义解释,按照位置的顺序:

      年,月,日,时,分,秒,周几,儒历日,夏令时。

    >>> 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

      shelve模块可以使用Python默认的存储,将数据存储至指定的文件名中,使用open方法从文件中读取数据,对数据做修改后需要使用close方法将改动写入到磁盘中。

    >>> 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()

      测试数据是否写入到磁盘中

    >>> import shelve

    >>> s = shelve.open("test.dat")

    >>> s["x"]

    ['a', 'b', 'c', 'd']

      在pyhon的安装目录下可以找到test.dat文件。

      shelve模块操作的文件中的数据也是也键值对的形式存在的,和字典的区别是字典中的数据没有存储到硬盘中,重启后会丢失,shelve则是将数据写入到硬盘中。

      re模块提供了正则表达式的支持。

      对文件的操作

    >>> f =open("some.txt","w")

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

    6

    >>> f.write("world")

    5

    >>> f.close()

      在Python的安装路径下可以找到名为some.txt的新创建的文件。

      读取文件的操作:

    >>> file = open(r"F:pythonpythonexesome.txt")

      f =open("some.txt","w")中第二个参数的含义:

      w—写模式,r—读模式,+—读写模式,a—追加模式,b—二进制模式

      如果处理的文件是二进制文件,如声音,视频文件就需要使用b参数,如果只是读取一个二进制文件,第二个参数就可以使用rb的参数。

      open函数的的第三个参数控制的是缓存,缓存是指使用内存来代替硬盘进行文件读取,程序速度会更快,使用flush或者close才会将缓存中的数据写入到硬盘中。

      当open函数的的第三个参数是0时表示不使用缓存,为负数时表示使用默认的缓存,大于1的数字表示缓存的大小(单位是字节)。

    >>> f = open("some.txt","r")

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

    'hell'

    >>> f.read()

    'o,world'

      readline和writelines可以读取或者写入一行的字符。

      write和writelines默认都是会覆盖文件中原来的内容。

      需要使用追加模式,f = open("some.txt","a")

      Python对文件的操作最后都应该做关闭操作,例如对文件做写操作,修改可能还在缓存中时程序崩溃了,如果不做写操作,所做的修改就会完全的丢失。

      文件的关闭应该放到finally中完成:

    try:

             f = open("some.txt","r")

             #else code

    finally:

             f.close()

      关于换行的一些注意,不需要再做转义,否则不能换行。

    >>> f= open("some.txt","a")

    >>> f.write("append line ")

      可以看到Python中的文件流最后读到的是空字符串,不是Java中的-1

    >>> 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都为False

      循环处理每个字符

    >>> f= open("some.txt","r

    >>> while(True):

    ...    char = f.read(1)

    ...    if not char:break

    ...    else:

    ...        print(char)

    >>>f.close()

  • 相关阅读:
    【Python大系】Python快速教程
    【Linux大系】Linux的概念与体系
    【Java大系】Java快速教程
    【夯实PHP系列】PHP正则表达式
    【PHP夯实基础系列】PHP日期,文件系统等知识点
    【夯实PHP系列】购物车代码说明PHP的匿名函数
    2016.09.21 公司裁员想到的
    使用android-junit-report.jar导出单元测试报告
    APK无源码使用Robotium简单总结
    Android环境安装简单总结
  • 原文地址:https://www.cnblogs.com/lnlvinso/p/3923477.html
Copyright © 2011-2022 走看看