美文网首页
python 基础

python 基础

作者: 捂口骑士 | 来源:发表于2018-01-18 08:55 被阅读0次

1 基础

  • 基本数据类型:int float str bool,类型转换:int() float() str()

  • + - * / // % **

  • 0b 0B 二进制;0o 0O 八进制;0x 0X 十进制

  • 切片:[start : end : step]

  • list tuple dict setlist() tuple() dict() set()

  • [x for x in range(1,9) if x%2 == 0]

  • ''' long long string can change line'''

    除了用于文本,还有package和function的文档说明。

  • if condiction: ... elif condiction: ... else: ...

  • while condiction: ... else: ...

  • for condiction: ... else: ...

2 模块与包

  • 导入模块或包

    import packagename
    import packagename as pn
    from random import choice
    
  • python 标准库

  • 模板

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    
    ' a test module '
    
    __author__ = 'Michael Liao'
    
    import sys
    
    def test():
        args = sys.argv
        if len(args)==1:
            print('Hello, world!')
        elif len(args)==2:
            print('Hello, %s!' % args[1])
        else:
            print('Too many arguments!')
    
    if __name__=='__main__':
        test()
    

3 函数

  • 内建函数

    help() type() repr()
    len() sorted() dir()
    encode() decode()
    format()
    
    map(function, iter)
    #对iter中的每个元素执行function操作
    
    reduce(function, iter)
    #等价于
    result = function(iter[0], iter[1])
    result = function(result, iter[2])
    ...
    result = function(result, iter[-1])
    
    filter(function, iter)
    
  • 自定义函数

    #function of python
    def function(*args) #调用时对应的参数打包成一个名为args的list送入函数
    def function(**kwargs) #调用时对应的参数打包成一个名为kwargs的dict送入函数
    
    def function():
        'this is a function doc'
        pass
    def function():
        ''' this is a function doc's first line;
        this is a function doc's second line.'''
        pass
    print(function.__doc__) #输出函数的文档
    
    print(function.__name__) #输出函数的名字
    
    def func_a():
        pass
    def func_b(func_a): #函数是一级公民
        func_a()
        
    def outer():
        def inner(): #函数内部定义函数
            pass
        
    #闭包 用一个函数定义生成一组类似的函数
    def write_log(error_type):
        def print_log():
            return 'error type is: ' + error_type
        return print_log
    a = write_log('disk error')
    b = write_log('memory error')
    #a,b是不同的函数
    
    #匿名函数
    def print_result(result, function):
        for number in result:
            print(function(number))
    #example
    result = [1,2,3,4,5]
    print_result(result, lambda number: number ** 5)
    
    #生成器
    def my_range(start, end, step):
        number = first
        while number < end:
            yield number
            number += step
    a = my_range(1,5,1)
    #a的类型是生成器,和range()返回的结果类似
    
    #修饰器
    def document_it(func):
        def new_function(*args, **kwargs):
            print('Running function:', func.__name__)
            print('Positional arguments:', args)
            print('Keyword arguments:', kwargs)
            result = func(*args, **kwargs)
            print('Result:', result)
            return result
        return new_function
    @document_it
    def add_int(a, b):
        return a+b
    #等价于
    add_int = document_it(lambda a,b: a+b)
    

4 对象

#class of python
class Car():
    def __init__(self, color): #初始化
        self.color = color
class Yugo(Car): #继承
    pass
#继承可以得到父类的方法,但是也可以重写此方法进行重载
#在子类的定义中,super()是指父类,以此使用父类中的定义
#在定义某个以父类作为参数的函数之后,其对子类使用这个函数(由于多态)

#直接定义的属性不够安全,没有进行检查
class Car():
    def __init__(self, value):
        self.color = value
    @property #通过property修饰,定义访问car.color时的行为
    def color(self):
        return 'the color is: ' + self._color
    @color.setter #通过setter修饰,定义对car.color赋值时的行为
    def color(self,value):
        self._color = value

class Car():
    def __init__(self, value):
        self.__color = value #__color是无法直接访问的

class Car():
    n = 0
    def __init__(self):
        n += 1
    @classmethod #使用classmethod修饰,定义一个类方法
    def counter(cls): #这里的例子是一个计数器,记录用Car生成了多少实例
        return cls.n

#定义类的特殊方法
#__eq__, __ne__, __lt__, __gt__, __le__, __ge__
#__add__, __sub__, __mul__, __truediv__, __floordiv__, __mod__, __pow__
#__str__, __len__, __repr__
#__iter__, __next__ 用于for ... in ...循环时的行为
#__getitem__, 用于切片时的行为
#__call__, 用于定义调用该实例时的行为

5 文件

fileobj = open('path/filename', 'mode')
#mode为两个字符,前一个为rwxa中的一个,为只读、写入、新建文件并写入、在结尾增添;后一个为bt中的一个,表示二进制文件和文本文件
    
fileobj.close()
with open('path/filename', 'mode') as f: #无需进行f.close()
    f.dosomething
    
fileobj.write(things)
print(things, file = fileobj)
    
text = fileobj.read(position) #读取position之后的所有内容
text = fileobj.readline() #读取一行
    
position = fileobj.tell() #获取文件指针的位置
fileobj.seek(offset, origin) #设置文件指针到origin之后offset处

6 异常与错误

try:
    pass
except ErrorType as a:
    print('there is a ',a)
finally:
    pass

#抛出错误
raise ErrorType(text)

#断言,用于调试
assert n!=0, 'n is zero' #如果为假,则输出后面的文本

相关文章

网友评论

      本文标题:python 基础

      本文链接:https://www.haomeiwen.com/subject/rjdioxtx.html