Python:考点总结+示例程序

考试题型:判断15,选择20,填空10,简答3,分析4(代码写结果,4*5),程序2


基础

作者,Guido van Rossum 圣诞节 荷兰

大小写敏感

换行和缩进

保留字(35)

import keyword

print(len(keyword.kwlist))
print(keyword.kwlist)

'''
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await',
 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 
 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 
 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 
 'return', 'try', 'while', 'with', 'yield']
'''

异常处理

# demo1
try:
    1 / 0
except ZeroDivisionError:  # 异常时执行
    print("error")
else:  # 无异常时执行
    print("no error")
finally:  # 清理行为,不管有没有异常,finally 都会执行
    print("no matter")

# demo2 预定义清理行为
try:
    with open('test.txt') as f:
        for line in f:
            print(line)
except FileNotFoundError as e:
    print("error", e)

# demo3
try:
    1 / 1
except ZeroDivisionError:  # 异常时执行
    print("error")
else:  # 无异常时执行
    print("no error")
finally:  # 清理行为,不管有没有异常,finally 都会执行
    print("no matter")

# demo4
try:
    1 / 0
except ZeroDivisionError as e:
    print("error:", e)
else:
    print("no error")

# demo5
try:
    a = int('a')
    1 / 0
except (ZeroDivisionError, ValueError) as e:
    print("error:", e)
else:
    print("no error")

# demo6
try:
    raise ZeroDivisionError('hi')
except ZeroDivisionError as e:
    print("error:", e)
    # raise  # 将捕获到的异常再次抛出
else:
    print("no error")
'''

output

error
no matter
error [Errno 2] No such file or directory: 'test.txt'
no error
no matter
error: division by zero
error: invalid literal for int() with base 10: 'a'
error: hi

import、引用和注释

import numpy
from numpy import add_newdocs
import numpy.add_newdocs

a = 'a'
a = "a"
a = '''a'''

# 单行注释

'''
单引号多行注释
'''

"""
双引号多行注释
"""

变量赋值

a = b = c = 1
print(a, b, c)
a, b, c = 1, [1, 2], (1,)
print(a, b, c)

基本数据类型

Numbers 只有三种:int,float,complex,只在 python2 中有 long

a = int(1)
print(a)
a = float(1)
print(a)
a = complex(1)
print(a)
a = complex(1, 2)
print(a)
a = 1 + 2j
print(a)
print(type(a))

String

a = "hello WORLD"

print(a.upper())
print(a.lower())
print(a.capitalize())

print(a.startswith('h'))
print(a.startswith('e', 1, 3))

a = " hello WORLD "
print(a.lstrip())
print(a.rstrip())
print(a.strip())

print(a.split())

a = "abcd"
print(list(a))
print(max(a))
print(min(a))

a = """one
two
three"""
print(a)
print(a.splitlines())

a = """
one
two
three
"""
print(a)
print(a.splitlines())

a = 'abc'.join(['1', '2', '3'])
print(a)

print(a.index("b"))

b = a.encode(encoding='utf-8')
print(b)
print(b.decode(encoding='utf-8'))

格式化字符串

# 1.
a = "str"
print(a.center(5, '-'))

# 2.
print("str: %5s" % a)  # 没有逗号,加两次%,只有一个参数为元组
print("str: %5s, num: %d" % (a, 123))  # 没有逗号,加两次%,只有一个参数为元组

# 3.
print("{server} {0}:{1}".format("127.0.0.1", "8080", server="Web Server"))
print("{0[0]} {0[1]}:{0[2]}".format(("Web Server", "127.0.0.1", "8080")))

print("{0:@^5}*{1:&<5}={2:#>5}".format(3, 2, 2 * 3))

列表

a = [4, 2, 3]
a.reverse()
print(a)
a.sort()
print(a)
a.append([5, 6])
print(a)
a.extend([7, 8])
print(a)
a.extend((9, 0))
print(a)
print(a.pop())
print(a)

列表切片

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a[::-1])
print(a[2:5:2])
print(a[5:2:-1])

# i=[ 0,   1,   2,   3,   4,   5]
# i=[-6,  -5,  -4,  -3,  -2,  -1]
a = ['A', 'B', 'C', 'D', 'E', 'F']
print(a[0:3])
print(a[0:-3])
print(a[-6:3])
print(a[-6:-3])

元组

a = (1)
print(type(a))
a = (1,)
print(type(a))
a = (1, 2, 3, 4, 5, 6)
print(a[1:])
print(a[-2])

字典的创建

a = {'abc': 123, 98.6: 37}
print(a)

a = {}
a['key'] = 'value'
print(a)

list1 = ['a', 'b', 'c'];
list2 = [1, 2, 3]
a = dict(zip(list1, list2))
print(a)

a = dict.fromkeys(['a', 'b', 'c'], [1, 2])
print(a)

字典的遍历

a = {'abc': 123, 98.6: 37}
for i in a:
    print(i)

a = {'abc': 123, 98.6: 37}
for i in a:
    print(a[i])

a = {'abc': 123, 98.6: 37}
for i in a.keys():
    print(a[i])

a = {'abc': 123, 98.6: 37}
for i in a.values():
    print(i)

a = {'abc': 123, 98.6: 37}
for i in a.items():
    print(i)

a = {'abc': 123, 98.6: 37}
for (k, v) in a.items():
    print(k, v)

集合

a = {1, 2, 3}
print(a)
print(type(a))

a = set((1, 2, 3))
print(a)
print(type(a))

a = {x for x in 'abracadabra' if x not in 'abc'}
print(a)

a.add('a')
print(a)
a.add('a')
print(a)

a = frozenset((1, 2))
print(a)

基本运算

±*/ // ** ^

print(21 / 10)
print(21 // 10)

print(2 ** 3)

print(2 ^ 3)  # 10^11=01
print(1 ^ 3)  # 01^11=10

赋值,引用,深拷贝,浅拷贝,拆包,装包

a = [1, 2, 3, [4, 5]]
b = a.copy()
b[0] = 'b'
print(a)
print(b)
b[3][0] = 'bb'
print(a)
print(b)

from copy import deepcopy

c = deepcopy(b)
c[3][0] = 'cc'
print(b)
print(c)

a = ('str', 123, '2018-12-12', [1, 2, 3], (4, 5, 6))
b, c, d, e, f = a
print(b)
print(c)
print(d)
print(e)
print(f)
*_, aa = a;  # *_ 为通配符
print(aa)
bb, *_, cc = a;
print(bb)
print(cc)

a = {'abc': 123, 12: 'ab', 32: 43}  # 字典拆包出来的仅是 key
b, c, d = a
print(b)
print(c)
print(d)

print(*a)  # 用*拆包
a = [1, 2, 3]
print(*a)
a = (1, 2, 3)
print(*a)
a = {1, 2, 3}
print(*a)


def run(a, *args):
    print(a)
    print(args)


run(1, 2, 3)


def run(**kwargs):  # 传来的 key = value 类型的实参会映射成kwargs里面的键和值
    # kwargs是一个字典,将未命名参数以键值对的形式
    print(kwargs)
    print("对kwargs拆包")
    run1(**kwargs)


def run1(a, b):  # 此处的参数名一定要和字典的键的名称一)
    print(a, b)


run(a=1, b=2)

总结:

  1. *args作为形参时是用来接收多余的未命名参数,而**kwargs是用来接收key=value这种类型的命名参数,args是元组,kwargs是字典。
  2. *和**在函数体中除了拆包之外,并没有什么卵用。
  3. 装包的含义就是把未命名参数和命名参数分别放在元组或者字典中。

关系运算,逻辑运算,位运算

  • == != > < <= >=
  • and or not
  • & | ^ >> <<

成员运算

a = {1, 2, 3}
print(1 in a)
print(2 not in a)

身份运算

a = 20
b = 20
print(a is b)
print(id(a), id(b))
b = 30
print(a is b)
print(a is not b)

is 与 == 区别:is 用于判断两个变量引用对象是否为同一个, == 用于判断引用变量的值是否相等。

a = [1, 2, 3]
b = a
print(b is a)
print(b == a)
b = a[:]
print(b is a)
print(b == a)

内置函数

print(dir(__builtins__))

print(eval("2+3*4"))

列表生成式,生成器,迭代器,map,reduce,filter,lambda

列表生成式

a = [x ** 2 for x in range(1, 10)]
b = [x * x for x in range(1, 11) if x % 2 == 0]
c = [m + n for m in 'ABC' for n in '123']
d = {'Java': "99", 'C': "99", 'C++': "99"}
L = [k + '=' + v for k, v in d.items()]
print(a)
print(b)
print(c)
print(L)

生成器

a = (x ** 2 for x in range(1, 10))
print(a)
print(a.__next__())
print(next(a))
print('-----')
for i in a:
    print(i)


def fibonacci(n):  # 生成器函数 - 斐波那契
    a, b, counter = 0, 1, 0
    while True:
        if counter >= n:
            return
        yield a
        a, b = b, a + b
        counter += 1


f = fibonacci(10)  # f 是一个迭代器,由生成器返回生成
print('fibonacci')
print(f)
print(next(f))
print(f.__next__())
print('-----')
for i in f:
    print(i)

生成器的 send

def average():
    s = 0
    count = 0
    avg = 0
    while True:
        num = yield avg
        s += num
        count += 1
        avg = s / count


avg_g = average()
# 第一次运行只能使用next或者send(None)
print(avg_g.__next__())
avg1 = avg_g.send(10)
print(avg1)
avg1 = avg_g.send(20)
print(avg1)
avg1 = avg_g.send(30)
print(avg1)

print('**********************************')


# 生成器的send用法 generator.send(value)
def test():
    i = 1
    while i < 5:
        temp = yield i ** 2
        print(temp)
        i += 1


t = test()
# 第一次运行只能使用next或者send(None)
print(t.__next__())
# send的作用相当于使生成器继续运行,并且传递的参数为yield的返回值(程序中即temp的值)
print(t.send("Hello World"))
print(t.__next__())  # 相当于send(None) 此时temp = None

迭代器

print('list_iter')
a = [1, 2, 3]
a = iter(a)
print(a)
print(next(a))
print(a.__next__())

print('str_iter')
a = '123'
a = iter(a)
print(a)
print(next(a))
print(a.__next__())

print('tuple_iter')
a = (1, 2, 3)
a = iter(a)
print(a)
print(next(a))
print(a.__next__())

print('set_iter')
a = {1, 2, 3}
a = iter(a)
print(a)
print(next(a))
print(a.__next__())

print('dict_iter')
a = {1: 'a', 2: 'b', 3: 'c'}
a = iter(a)
print(a)
print(next(a))
print(a.__next__())

Map

def f(x):
    return x * x


a = map(f, [1, 2, 3])
print(list(a))

print(list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])))

Reduce:Reduce 在 python3 中移除,需要 import

from functools import reduce


def add(a, b):
    return a + b


a = reduce(add, [1, 2, 3])
print(a)

Map-Reduce

def str2int(s):
    digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

    def fn(x, y):
        return x * 10 + y

    def char2num(s):
        return digits[s]

    return reduce(fn, map(char2num, s))


print(str2int('135'))

Filter

def is_odd(n):
    return n % 2 == 1


print(list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])))

分子筛求素数:

def primes():
    it = iter(range(2, 100))  # 初始序列

    def _not_divisible(n):
        return lambda x: x % n > 0

    while True:
        n = next(it)  # 返回序列的第一个数
        yield n
        it = filter(_not_divisible(n), it)  # 构造新序列


print('primes')
for n in primes():
    if n < 50:
        print(n)
    else:
        break

lambda

print(list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])))
f = lambda x: x * x
print(f(5))

正则表达式

match

s = 'ABC\\-001'
s = r'ABC\-001'

import re

# span:返回一个元组包含匹配(开始,结束)的位置
print(re.match('www', 'www.runoob.com').span())  # 在起始位置匹配
print(re.match('com', 'www.runoob.com'))  # 不在起始位置匹配

line = "Cats are smarter than dogs"
# .* 表示任意匹配除换行符(\n、\r)之外的任何单个或多个字符
matchObj = re.match(r'(.*) are (.*?) .*', line)

if matchObj:
    print("matchObj.groups() : ", matchObj.groups())
    print("matchObj.group() : ", matchObj.group())
    print("matchObj.group(1) : ", matchObj.group(1))
    print("matchObj.group(2) : ", matchObj.group(2))
    print("matchObj.group(1,2) : ", matchObj.group(1, 2))
else:
    print("No match!!")

贪婪模式:量词后面加?是非贪婪模式

print(re.match(r'^(\d+)(0*)$', '102300').groups())
# ('102300', '')
print(re.match(r'^(\d+?)(0*)$', '102300').groups())
# ('1023', '00')
# 由于\d+采用贪婪匹配,直接把后面的0全部匹配了,结果0*只能匹配空字符串,加个?就可以让\d+采用非贪婪匹配;

编译

# 如果一个正则表达式要重复使用几千次,出于效率的考虑,我们可以预编译该正则表达式
tel = re.compile(r'^(\d{3})-(\d{3,8})$')
# 使用:
print(tel.match('010-12345').groups())
# ('010', '12345')
print(tel.match('010-8086').groups())
# ('010', '8086')

search

print(re.search('www', 'www.runoob.com').span())  # 在起始位置匹配
print(re.search('com', 'www.runoob.com').span())  # 不在起始位置匹配

sub:检索和替换

phone = "2004-959-559 # 这是一个电话号码"

# 删除注释
num = re.sub(r'#.*$', "", phone)
print("电话号码 : ", num)

# 移除非数字的内容
num = re.sub(r'\D', "", phone)
print("电话号码 : ", num)


# 将匹配的数字乘于 2
def double(matched):
    value = int(matched.group())
    return str(value * 2)


s = 'A23G4HFD567'
print(re.sub(r'\d+', double, s))

findall

pattern = re.compile(r'\d+')  # 查找数字
result1 = pattern.findall('runoob 123 google 456')
result2 = pattern.findall('run88oob123google456', 4, 10)  # begin and end pos

print(result1)
print(result2)

finditer 和 spilt

it = re.finditer(r"\d+", "12a32bc43jf3")
for match in it:
    print(match.group())

print(re.split('\W+', 'runoob, runoob, runoob.'))

面向对象

class Base1:
    pass


class Base2:
    pass


class A(Base1, Base2):  # 继承
    class_attr = 0  # 类属性

    def __init__(self):
        self.__private_attrs = 0
        self.attrs = {}
        A.class_attr += 1

    def __private_method(self):
        print("__private_method")

    def __repr__(self):
        return 'be print'

    def __setitem__(self, key, value):
        self.attrs[key] = value

    def __getitem__(self, item):
        return self.attrs[item]


a = A()
print(a.__dict__)
print(a._A__private_attrs)
a.attr = "new attr"  # 为实例绑定属性
print(a.__dict__)

a._A__private_method()


def func(self):
    print('new func')


from types import MethodType

a.func = MethodType(func, a)  # 只为实例 a 绑定方法
a.func()

A.func = func  # 给类中所有实例绑定方法
a.func()

print(a)

a['1'] = 2
print(a.__dict__)
print(a['1'])

print(A.class_attr)


class Student(object):
    __slots__ = ('name', 'age')  # 用tuple定义允许绑定的属性名称


# 使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的。除非在子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__。

使用@property

Python内置的@property装饰器就是负责把一个方法变成属性调用的。把一个getter方法变成属性,只需要加上@property就可以了,此时,@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值。

class Student(object):
    def __init__(self):
        self.__score = 0

    @property
    def score(self):
        return self.__score

    @score.setter
    def score(self, value):
        self.__score = value


a = Student()
print(a.score)
a.score = 123
print(a.score)


class Animal(object):
    def __init__(self, name, age):
        self._name = name

    def get_name(self):
        return self._name

    def set_name(self, value):
        self._name = value

    name = property(fget=get_name, fset=set_name, fdel=None, doc='name of an animal')


a = Animal('black dog', 3)
print(a.name)
a.name = 'white dog'
print(a.name)
print(Animal.name.__doc__)

继承:MRO

# 双叉树继承

class D:
    pass


class E:
    pass


class C(E):
    pass


class B(D):
    pass


class A(B, C):
    pass


print(A.__mro__)


# 菱形继承

class A:
    pass


class B(A):
    pass


class C(A):
    pass


class D(B, C):
    pass


print(D.__mro__)

多态

由于Python是动态语言,所以,传递给函数work_with_dog的参数dog不一定是Dog或Dog的子类型。任何数据类型的实例都可以,只要它有一个work()的方法即可:
class Book(object):
def work():
print('这是一本书’)
这是动态语言和静态语言(例如Java)最大的差别之一。动态语言调用实例方法,不检查类型,只要方法存在,参数正确,就可以调用。

子类可以重写父类方法,在子类中也可以调用父类的方法。

class A:
    def fun(self):
        print("A")


class B(A):
    def fun(self):
        print("B")


a = B()
a.fun()
super(B, a).fun()

对象三要素:value、type、id

判断是否相等:
value: ==
type: isinstance(x, A_tuple),type() 取出类型值
id: is 直接判断,id() 取出身份值

type() 和 isinstance() 函数的区别:

  • isinstance(object, classinfo)判断参数 object 是否是 classinfo 类或者其子类的实例
  • type()只能判断是否是该类本身的实例
print(type(a))
print(A)
print(isinstance(a, A))
print(isinstance(B, A))
print(type(B))
print(type(B) is type)
print(B)
print(isinstance(B, type))

魔法函数

with语句:

  • __enter__始
  • __exit__终

实现 def iter(self):方法才有迭代器。

python语法会做一些优化,如果拿不到迭代器(即没有实现__iter__方法),python解释器会去寻找__getitem__()方法,直到整个对象取完。

class A:
    def __init__(self):
        self.__e = [1, 2, 3, 4, 5]

    def __iter__(self):
        self.__count = -1
        return self

    def __next__(self):
        if self.__count > 3:
            raise StopIteration
        else:
            self.__count += 1
            return self.__e[self.__count]


a = A()
for i in a:
    print(i)

静态方法和类方法

  • 静态方法: 用 @staticmethod 装饰的不带 self 参数的方法叫做静态方法,类的静态方法可以没有参数,可以直接使用类名调用。
  • 普通方法: 默认有个self参数,且只能被对象调用。
  • 类方法: 默认有个 cls 参数,可以被类和对象调用,需要加上 @classmethod 装饰器。
class A:
    class_attr = 1

    @staticmethod
    def s_func():
        print("static method")

    @classmethod
    def c_func(cls):
        print("class method")
        print(cls.class_attr)


a = A()
a.s_func()
A.s_func()
a.c_func()
A.c_func()

抽象基类

  • @abc.abstractmethod 装饰器,将方法声明为抽象方法。
  • @abc.abstractclassmethod 装饰器,将方法声明为抽象类方法。
  • @abc.abstractstaticmethod 装饰器,将方法声明为抽象静态方法。
  • @abc.abstractproperty 装饰器,声明为抽象属性。
  • abc.ABCMeta 生成抽象基础类的元类。
  • abc.ABC辅助类,让我们可以不用关心元类概念,直接继承它,就有了ABCMeta元类。
from abc import ABCMeta, abstractmethod


class A(metaclass=ABCMeta):

    @abstractmethod
    def fun(self):
        pass

注册具体类:

调用抽象基类的register 方法,来把其他类注册到抽象基类下。这种方法实现的,我们称之为称为虚拟子类。

注册方式的特点:

  1. 虚拟子类可以实现抽象基类中的部分API接口,也可以根本不实现,但是issubclass(), issubinstance()进行判断时仍然返回真值。当没有实现抽象方法时,实例化时候不会报错,只有在调用时候才会报错。
  2. 父类不会出现在类的MRO (Method Resolution Order),故而也不能通过super()来调用父类的方法。
class B:
    pass

print(issubclass(B,A))
print(isinstance(B(),A))
A.register(B)
print(issubclass(B,A))
print(isinstance(B(),A))

装饰器

# 1:装饰器在后

def fun():
    print("fun")


def dec(f):
    def wrapper():
        print('begin')
        f()
        print('end')

    return wrapper  # 没有括号


fun()
fun = dec(fun)  # 没有括号
fun()


# 2:装饰器在前

def dec(f):
    def wrapper():
        print('begin')
        f()
        print('end')

    return wrapper  # 没有括号


@dec
def fun():
    print("fun")


fun()

测试

def bold(fun):
    print('---a---')

    def inner():
        print('---1---')
        return "<b>" + fun() + "</b>"

    return inner


def italic(fun):
    print('---b---')

    def inner():
        print('---2---')
        return "<i>" + fun() + "</i>"

    return inner


@bold
@italic
def func():
    print('---c---')
    print('---3---')
    return 'hello world'


a = func()
print('=====')
print(a)

输出:

---b---
---a---
---1---
---2---
---c---
---3---
=====
<b><i>hello world</i></b>

闭包

用途1:当闭包执行完后,仍然能够保持住当前的运行环境。
用途2:闭包可以根据外部作用域的局部变量来得到不同的结果,这有点像一种类似配置功能的作用,我们可以修改外部的变量,闭包根据这个变量展现出不同的功能。

def addx(x):
    def adder(y): return x + y

    return adder


c = addx(8)
print(type(c))
print(c(10))

flist = []
for i in range(3):
    def foo(x):
        print(x + i)


    flist.append(foo)
for f in flist:
    f(2)

'''
可能有些人认为这段代码的执行结果应该是2,3,4.但是实际的结果是4,4,4。这是因为当把函数加入flist列表里时,python还没有给i赋值,只有当执行时,再去找i的值是什么,这时在第一个for循环结束以后,i的值是2,所以以上代码的执行结果是4,4,4。
'''

# 改进

for i in range(3):
    def foo(x, y=i):
        print(x + y)


    flist.append(foo)

for f in flist:
    f(2)


# 用途1:每次移动棋子基于上次的位置

def create(pos=[0, 0]):
    # pos 为 create 中的变量,每次调用 player 都在改变它的值
    def player(direction, step):
        new_x = pos[0] + direction[0] * step
        new_y = pos[1] + direction[1] * step
        pos[0] = new_x
        pos[1] = new_y
        return pos

    return player


player = create()  # 创建棋子player,起点为原点
print(player([1, 0], 10))  # 向x轴正方向移动10步
print(player([0, 1], 20))  # 向y轴正方向移动20步
print(player([-1, 0], 10))  # 向x轴负方向移动10步

带参数的迭代器

def logged(priority, module='__main__', msg=''):
    # 外部为闭包,内部为装饰器
    def decorate(func):
        def wrapper(*arg, **kwargs):
            print("log[priority:", priority, ', module:', module, ', msg:', msg, ']')
            return func(*arg, *kwargs)

        return wrapper

    return decorate


@logged(0, 'add', 'add x and y')
def add(x, y):
    return x + y


@logged(2)
def spam():
    print('Spam!')


print(add(3, 4))
spam()


语法糖

https://blog.csdn.net/five3/article/details/83474633


附录:示例程序

###############################################################
# 保留字

import keyword

print(len(keyword.kwlist))
print(keyword.kwlist)

'''
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await',
 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 
 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 
 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 
 'return', 'try', 'while', 'with', 'yield']
'''

###############################################################
# 异常

# demo1
try:
    1 / 0
except ZeroDivisionError:  # 异常时执行
    print("error")
else:  # 无异常时执行
    print("no error")
finally:  # 清理行为,不管有没有异常,finally 都会执行
    print("no matter")

# demo2 预定义清理行为
try:
    with open('test.txt') as f:
        for line in f:
            print(line)
except FileNotFoundError as e:
    print("error", e)

# demo3
try:
    1 / 1
except ZeroDivisionError:  # 异常时执行
    print("error")
else:  # 无异常时执行
    print("no error")
finally:  # 清理行为,不管有没有异常,finally 都会执行
    print("no matter")

# demo4
try:
    1 / 0
except ZeroDivisionError as e:
    print("error:", e)
else:
    print("no error")

# demo5
try:
    a = int('a')
    1 / 0
except (ZeroDivisionError, ValueError) as e:
    print("error:", e)
else:
    print("no error")

# demo6
try:
    raise ZeroDivisionError('hi')
except ZeroDivisionError as e:
    print("error:", e)
    # raise  # 将捕获到的异常再次抛出
else:
    print("no error")

###############################################################
# import,引用和注释

import numpy
from numpy import add_newdocs
import numpy.add_newdocs

a = 'a'
a = "a"
a = '''a'''

# 单行注释

'''
单引号多行注释
'''

"""
双引号多行注释
"""

###############################################################
# 变量赋值

a = b = c = 1
print(a, b, c)
a, b, c = 1, [1, 2], (1,)
print(a, b, c)

###############################################################
# 基本数据类型

# Numbers 只有三种:int,float,complex,只在 python2 中有 long

a = int(1)
print(a)
a = float(1)
print(a)
a = complex(1)
print(a)
a = complex(1, 2)
print(a)
a = 1 + 2j
print(a)
print(type(a))

# String

a = "hello WORLD"

print(a.upper())
print(a.lower())
print(a.capitalize())

print(a.startswith('h'))
print(a.startswith('e', 1, 3))

a = " hello WORLD "
print(a.lstrip())
print(a.rstrip())
print(a.strip())

print(a.split())

a = "abcd"
print(list(a))
print(max(a))
print(min(a))

a = """one
two
three"""
print(a)
print(a.splitlines())

a = """
one
two
three
"""
print(a)
print(a.splitlines())

a = 'abc'.join(['1', '2', '3'])
print(a)

print(a.index("b"))

b = a.encode(encoding='utf-8')
print(b)
print(b.decode(encoding='utf-8'))

# 格式化字符串

# 1.
a = "str"
print(a.center(5, '-'))

# 2.
print("str: %5s" % a)  # 没有逗号,加两次%,只有一个参数为元组
print("str: %5s, num: %d" % (a, 123))  # 没有逗号,加两次%,只有一个参数为元组

# 3.
print("{server} {0}:{1}".format("127.0.0.1", "8080", server="Web Server"))
print("{0[0]} {0[1]}:{0[2]}".format(("Web Server", "127.0.0.1", "8080")))

print("{0:@^5}*{1:&<5}={2:#>5}".format(3, 2, 2 * 3))

# List

a = [4, 2, 3]
a.reverse()
print(a)
a.sort()
print(a)
a.append([5, 6])
print(a)
a.extend([7, 8])
print(a)
a.extend((9, 0))
print(a)
print(a.pop())
print(a)

# 列表切片

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a[::-1])
print(a[2:5:2])
print(a[5:2:-1])

# i=[ 0,   1,   2,   3,   4,   5]
# i=[-6,  -5,  -4,  -3,  -2,  -1]
a = ['A', 'B', 'C', 'D', 'E', 'F']
print(a[0:3])
print(a[0:-3])
print(a[-6:3])
print(a[-6:-3])

# 元组

a = (1)
print(type(a))
a = (1,)
print(type(a))
a = (1, 2, 3, 4, 5, 6)
print(a[1:])
print(a[-2])

# 字典

a = {'abc': 123, 98.6: 37}
print(a)

a = {}
a['key'] = 'value'
print(a)

list1 = ['a', 'b', 'c'];
list2 = [1, 2, 3]
a = dict(zip(list1, list2))
print(a)

a = dict.fromkeys(['a', 'b', 'c'], [1, 2])
print(a)

# 字典的遍历

a = {'abc': 123, 98.6: 37}
for i in a:
    print(i)

a = {'abc': 123, 98.6: 37}
for i in a:
    print(a[i])

a = {'abc': 123, 98.6: 37}
for i in a.keys():
    print(a[i])

a = {'abc': 123, 98.6: 37}
for i in a.values():
    print(i)

a = {'abc': 123, 98.6: 37}
for i in a.items():
    print(i)

a = {'abc': 123, 98.6: 37}
for (k, v) in a.items():
    print(k, v)

# 集合

a = {1, 2, 3}
print(a)
print(type(a))

a = set((1, 2, 3))
print(a)
print(type(a))

a = {x for x in 'abracadabra' if x not in 'abc'}
print(a)

a.add('a')
print(a)
a.add('a')
print(a)

a = frozenset((1, 2))
print(a)

###############################################################
# 基本运算

# +-*/ // ** ^

print(21 / 10)
print(21 // 10)

print(2 ** 3)

print(2 ^ 3)  # 10^11=01
print(1 ^ 3)  # 01^11=10

# 赋值,引用,深拷贝,浅拷贝,拆包,装包

a = [1, 2, 3, [4, 5]]
b = a.copy()
b[0] = 'b'
print(a)
print(b)
b[3][0] = 'bb'
print(a)
print(b)

from copy import deepcopy

c = deepcopy(b)
c[3][0] = 'cc'
print(b)
print(c)

a = ('str', 123, '2018-12-12', [1, 2, 3], (4, 5, 6))
b, c, d, e, f = a
print(b)
print(c)
print(d)
print(e)
print(f)
*_, aa = a;  # *_ 为通配符
print(aa)
bb, *_, cc = a;
print(bb)
print(cc)

a = {'abc': 123, 12: 'ab', 32: 43}  # 字典拆包出来的仅是 key
b, c, d = a
print(b)
print(c)
print(d)

print(*a)  # 用*拆包
a = [1, 2, 3]
print(*a)
a = (1, 2, 3)
print(*a)
a = {1, 2, 3}
print(*a)


def run(a, *args):
    print(a)
    print(args)


run(1, 2, 3)


def run(**kwargs):  # 传来的 key = value 类型的实参会映射成kwargs里面的键和值
    # kwargs是一个字典,将未命名参数以键值对的形式
    print(kwargs)
    print("对kwargs拆包")
    run1(**kwargs)


def run1(a, b):  # 此处的参数名一定要和字典的键的名称一)
    print(a, b)


run(a=1, b=2)

# 总结:
# 1. *args作为形参时是用来接收多余的未命名参数,而**kwargs是用来接收key=value这种类型的命名参数,args是元组,kwargs是字典。
# 2. *和**在函数体中除了拆包之外,并没有什么卵用。
# 3. 装包的含义就是把未命名参数和命名参数分别放在元组或者字典中。

# 关系运算,逻辑运算,位运算

# == != > < <= >=
# and or not
# & | ^ >> <<

# 成员运算

a = {1, 2, 3}
print(1 in a)
print(2 not in a)

# 身份运算

a = 20
b = 20
print(a is b)
print(id(a), id(b))
b = 30
print(a is b)
print(a is not b)

# is 与 == 区别:
# is 用于判断两个变量引用对象是否为同一个, == 用于判断引用变量的值是否相等。

a = [1, 2, 3]
b = a
print(b is a)
print(b == a)
b = a[:]
print(b is a)
print(b == a)

###############################################################
# 内置函数

print(dir(__builtins__))

print(eval("2+3*4"))

###############################################################
# 列表生成式,生成器,迭代器,map,reduce,filter,lambda

# 列表生成式

a = [x ** 2 for x in range(1, 10)]
b = [x * x for x in range(1, 11) if x % 2 == 0]
c = [m + n for m in 'ABC' for n in '123']
d = {'Java': "99", 'C': "99", 'C++': "99"}
L = [k + '=' + v for k, v in d.items()]
print(a)
print(b)
print(c)
print(L)

# 生成器

a = (x ** 2 for x in range(1, 10))
print(a)
print(a.__next__())
print(next(a))
print('-----')
for i in a:
    print(i)


def fibonacci(n):  # 生成器函数 - 斐波那契
    a, b, counter = 0, 1, 0
    while True:
        if counter >= n:
            return
        yield a
        a, b = b, a + b
        counter += 1


f = fibonacci(10)  # f 是一个迭代器,由生成器返回生成
print('fibonacci')
print(f)
print(next(f))
print(f.__next__())
print('-----')
for i in f:
    print(i)


# 生成器的 send

def average():
    s = 0
    count = 0
    avg = 0
    while True:
        num = yield avg
        s += num
        count += 1
        avg = s / count


avg_g = average()
# 第一次运行只能使用next或者send(None)
print(avg_g.__next__())
avg1 = avg_g.send(10)
print(avg1)
avg1 = avg_g.send(20)
print(avg1)
avg1 = avg_g.send(30)
print(avg1)

print('**********************************')


# 生成器的send用法 generator.send(value)
def test():
    i = 1
    while i < 5:
        temp = yield i ** 2
        print(temp)
        i += 1


t = test()
# 第一次运行只能使用next或者send(None)
print(t.__next__())
# send的作用相当于使生成器继续运行,并且传递的参数为yield的返回值(程序中即temp的值)
print(t.send("Hello World"))
print(t.__next__())  # 相当于send(None) 此时temp = None

# 迭代器

print('list_iter')
a = [1, 2, 3]
a = iter(a)
print(a)
print(next(a))
print(a.__next__())

print('str_iter')
a = '123'
a = iter(a)
print(a)
print(next(a))
print(a.__next__())

print('tuple_iter')
a = (1, 2, 3)
a = iter(a)
print(a)
print(next(a))
print(a.__next__())

print('set_iter')
a = {1, 2, 3}
a = iter(a)
print(a)
print(next(a))
print(a.__next__())

print('dict_iter')
a = {1: 'a', 2: 'b', 3: 'c'}
a = iter(a)
print(a)
print(next(a))
print(a.__next__())


# Map

def f(x):
    return x * x


a = map(f, [1, 2, 3])
print(list(a))

print(list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])))

# Reduce
# Reduce 在 python3 中移除,需要 import

from functools import reduce


def add(a, b):
    return a + b


a = reduce(add, [1, 2, 3])
print(a)


# Map-Reduce

def str2int(s):
    digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

    def fn(x, y):
        return x * 10 + y

    def char2num(s):
        return digits[s]

    return reduce(fn, map(char2num, s))


print(str2int('135'))


# Filter

def is_odd(n):
    return n % 2 == 1


print(list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])))


# 分子筛求素数

def primes():
    it = iter(range(2, 100))  # 初始序列

    def _not_divisible(n):
        return lambda x: x % n > 0

    while True:
        n = next(it)  # 返回序列的第一个数
        yield n
        it = filter(_not_divisible(n), it)  # 构造新序列


print('primes')
for n in primes():
    if n < 50:
        print(n)
    else:
        break

# lambda

print(list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])))
f = lambda x: x * x
print(f(5))

###############################################################
# 正则表达式

# match

s = 'ABC\\-001'
s = r'ABC\-001'

import re

# span:返回一个元组包含匹配(开始,结束)的位置
print(re.match('www', 'www.runoob.com').span())  # 在起始位置匹配
print(re.match('com', 'www.runoob.com'))  # 不在起始位置匹配

line = "Cats are smarter than dogs"
# .* 表示任意匹配除换行符(\n、\r)之外的任何单个或多个字符
matchObj = re.match(r'(.*) are (.*?) .*', line)

if matchObj:
    print("matchObj.groups() : ", matchObj.groups())
    print("matchObj.group() : ", matchObj.group())
    print("matchObj.group(1) : ", matchObj.group(1))
    print("matchObj.group(2) : ", matchObj.group(2))
    print("matchObj.group(1,2) : ", matchObj.group(1, 2))
else:
    print("No match!!")

# 贪婪模式:量词后面加?是非贪婪模式

print(re.match(r'^(\d+)(0*)$', '102300').groups())
# ('102300', '')
print(re.match(r'^(\d+?)(0*)$', '102300').groups())
# ('1023', '00')
# 由于\d+采用贪婪匹配,直接把后面的0全部匹配了,结果0*只能匹配空字符串,加个?就可以让\d+采用非贪婪匹配;

# 编译

# 如果一个正则表达式要重复使用几千次,出于效率的考虑,我们可以预编译该正则表达式
tel = re.compile(r'^(\d{3})-(\d{3,8})$')
# 使用:
print(tel.match('010-12345').groups())
# ('010', '12345')
print(tel.match('010-8086').groups())
# ('010', '8086')

# search

print(re.search('www', 'www.runoob.com').span())  # 在起始位置匹配
print(re.search('com', 'www.runoob.com').span())  # 不在起始位置匹配

# 检索和替换:sub

phone = "2004-959-559 # 这是一个电话号码"

# 删除注释
num = re.sub(r'#.*$', "", phone)
print("电话号码 : ", num)

# 移除非数字的内容
num = re.sub(r'\D', "", phone)
print("电话号码 : ", num)


# 将匹配的数字乘于 2
def double(matched):
    value = int(matched.group())
    return str(value * 2)


s = 'A23G4HFD567'
print(re.sub(r'\d+', double, s))

# findall

pattern = re.compile(r'\d+')  # 查找数字
result1 = pattern.findall('runoob 123 google 456')
result2 = pattern.findall('run88oob123google456', 4, 10)  # begin and end pos

print(result1)
print(result2)

# finditer 和 spilt

it = re.finditer(r"\d+", "12a32bc43jf3")
for match in it:
    print(match.group())

print(re.split('\W+', 'runoob, runoob, runoob.'))


###############################################################
# 面向对象

class Base1:
    pass


class Base2:
    pass


class A(Base1, Base2):  # 继承
    class_attr = 0  # 类属性

    def __init__(self):
        self.__private_attrs = 0
        self.attrs = {}
        A.class_attr += 1

    def __private_method(self):
        print("__private_method")

    def __repr__(self):
        return 'be print'

    def __setitem__(self, key, value):
        self.attrs[key] = value

    def __getitem__(self, item):
        return self.attrs[item]


a = A()
print(a.__dict__)
print(a._A__private_attrs)
a.attr = "new attr"  # 为实例绑定属性
print(a.__dict__)

a._A__private_method()


def func(self):
    print('new func')


from types import MethodType

a.func = MethodType(func, a)  # 只为实例 a 绑定方法
a.func()

A.func = func  # 给类中所有实例绑定方法
a.func()

print(a)

a['1'] = 2
print(a.__dict__)
print(a['1'])

print(A.class_attr)


class Student(object):
    __slots__ = ('name', 'age')  # 用tuple定义允许绑定的属性名称


# 使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的。除非在子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__。

# 使用@property

# Python内置的@property装饰器就是负责把一个方法变成属性调用的。把一个getter方法变成属性,只需要加上@property就可以了,此时,@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值。

class Student(object):
    def __init__(self):
        self.__score = 0

    @property
    def score(self):
        return self.__score

    @score.setter
    def score(self, value):
        self.__score = value


a = Student()
print(a.score)
a.score = 123
print(a.score)


class Animal(object):
    def __init__(self, name, age):
        self._name = name

    def get_name(self):
        return self._name

    def set_name(self, value):
        self._name = value

    name = property(fget=get_name, fset=set_name, fdel=None, doc='name of an animal')


a = Animal('black dog', 3)
print(a.name)
a.name = 'white dog'
print(a.name)
print(Animal.name.__doc__)


# 继承:MRO

# 双叉树继承

class D:
    pass


class E:
    pass


class C(E):
    pass


class B(D):
    pass


class A(B, C):
    pass


print(A.__mro__)


# 菱形继承

class A:
    pass


class B(A):
    pass


class C(A):
    pass


class D(B, C):
    pass


print(D.__mro__)


# 多态

# 由于Python是动态语言,所以,传递给函数work_with_dog的参数dog不一定是Dog或Dog的子类型。任何数据类型的实例都可以,只要它有一个work()的方法即可:
# class Book(object):
#     def work():
#         print('这是一本书’)
# 这是动态语言和静态语言(例如Java)最大的差别之一。动态语言调用实例方法,不检查类型,只要方法存在,参数正确,就可以调用。

# 子类可以重写父类方法
# 在子类中也可以调用父类的方法

class A:
    def fun(self):
        print("A")


class B(A):
    def fun(self):
        print("B")


a = B()
a.fun()
super(B, a).fun()

# 对象三要素:value,type,id

'''
判断是否相等:
value: ==
type: isinstance(x, A_tuple)
         type() 取出类型值
id: is 直接判断
     id() 取出身份值
     
type() 和 isinstance() 函数的区别:
isinstance(object, classinfo)
判断参数 object 是否是 classinfo 类或者其子类的实例
type()
只能判断是否是该类本身的实例

'''
print(type(a))
print(A)
print(isinstance(a, A))
print(isinstance(B, A))
print(type(B))
print(type(B) is type)
print(B)
print(isinstance(B, type))

# 魔法函数

'''
with语句
__enter__始
__exit__终

实现 def __iter__(self):方法才有迭代器
python语法会做一些优化,如果拿不到迭代器(即没有实现__iter__方法),python解释器会去寻找__getitem__()方法,直到整个对象取完

'''


class A:
    def __init__(self):
        self.__e = [1, 2, 3, 4, 5]

    def __iter__(self):
        self.__count = -1
        return self

    def __next__(self):
        if self.__count > 3:
            raise StopIteration
        else:
            self.__count += 1
            return self.__e[self.__count]


a = A()
for i in a:
    print(i)

# 静态方法和方法

'''
静态方法: 用 @staticmethod 装饰的不带 self 参数的方法叫做静态方法,类的静态方法可以没有参数,可以直接使用类名调用。

普通方法: 默认有个self参数,且只能被对象调用。

类方法: 默认有个 cls 参数,可以被类和对象调用,需要加上 @classmethod 装饰器。
'''


class A:
    class_attr = 1

    @staticmethod
    def s_func():
        print("static method")

    @classmethod
    def c_func(cls):
        print("class method")
        print(cls.class_attr)


a = A()
a.s_func()
A.s_func()
a.c_func()
A.c_func()

# 抽象基类

'''
@abc.abstractmethod 装饰器,将方法声明为抽象方法。
@abc.abstractclassmethod 装饰器,将方法声明为抽象类方法。
@abc.abstractstaticmethod 装饰器,将方法声明为抽象静态方法。
@abc.abstractproperty 装饰器,声明为抽象属性。
abc.ABCMeta 生成抽象基础类的元类。
abc.ABC辅助类,让我们可以不用关心元类概念,直接继承它,就有了ABCMeta元类。
'''

from abc import ABCMeta, abstractmethod


class A(metaclass=ABCMeta):

    @abstractmethod
    def fun(self):
        pass

'''
注册具体类:

调用抽象基类的register 方法,来把其他类注册到抽象基类下。
这种方法实现的,我们称之为称为虚拟子类。

注册方式的特点:
1.虚拟子类可以实现抽象基类中的部分API接口,也可以根本不实现,但是issubclass(), issubinstance()进行判断时仍然返回真值。当没有实现抽象方法时,实例化时候不会报错,只有在调用时候才会报错。
2.父类不会出现在类的MRO (Method Resolution Order),故而也不能通过super()来调用父类的方法。

'''

class B:
    pass

print(issubclass(B,A))
print(isinstance(B(),A))
A.register(B)
print(issubclass(B,A))
print(isinstance(B(),A))

###############################################################
# 装饰器

# 1:装饰器在后

def fun():
    print("fun")


def dec(f):
    def wrapper():
        print('begin')
        f()
        print('end')

    return wrapper  # 没有括号


fun()
fun = dec(fun)  # 没有括号
fun()


# 2:装饰器在前

def dec(f):
    def wrapper():
        print('begin')
        f()
        print('end')

    return wrapper  # 没有括号


@dec
def fun():
    print("fun")


fun()


# test 顺序

def bold(fun):
    print('---a---')

    def inner():
        print('---1---')
        return "<b>" + fun() + "</b>"

    return inner


def italic(fun):
    print('---b---')

    def inner():
        print('---2---')
        return "<i>" + fun() + "</i>"

    return inner


@bold
@italic
def func():
    print('---c---')
    print('---3---')
    return 'hello world'


a = func()
print('=====')
print(a)


# 闭包

# 用途1,当闭包执行完后,仍然能够保持住当前的运行环境。
# 用途2,闭包可以根据外部作用域的局部变量来得到不同的结果,这有点像一种类似配置功能的作用,我们可以修改外部的变量,闭包根据这个变量展现出不同的功能。

def addx(x):
    def adder(y): return x + y

    return adder


c = addx(8)
print(type(c))
print(c(10))

flist = []
for i in range(3):
    def foo(x):
        print(x + i)


    flist.append(foo)
for f in flist:
    f(2)

'''
可能有些人认为这段代码的执行结果应该是2,3,4.但是实际的结果是4,4,4。这是因为当把函数加入flist列表里时,python还没有给i赋值,只有当执行时,再去找i的值是什么,这时在第一个for循环结束以后,i的值是2,所以以上代码的执行结果是4,4,4。
'''

# 改进

for i in range(3):
    def foo(x, y=i):
        print(x + y)


    flist.append(foo)

for f in flist:
    f(2)


# 用途1:每次移动棋子基于上次的位置

def create(pos=[0, 0]):
    # pos 为 create 中的变量,每次调用 player 都在改变它的值
    def player(direction, step):
        new_x = pos[0] + direction[0] * step
        new_y = pos[1] + direction[1] * step
        pos[0] = new_x
        pos[1] = new_y
        return pos

    return player


player = create()  # 创建棋子player,起点为原点
print(player([1, 0], 10))  # 向x轴正方向移动10步
print(player([0, 1], 20))  # 向y轴正方向移动20步
print(player([-1, 0], 10))  # 向x轴负方向移动10步


# 带参数的装饰器

def logged(priority, module='__main__', msg=''):
    # 外部为闭包,内部为装饰器
    def decorate(func):
        def wrapper(*arg, **kwargs):
            print("log[priority:", priority, ', module:', module, ', msg:', msg, ']')
            return func(*arg, *kwargs)

        return wrapper

    return decorate


@logged(0, 'add', 'add x and y')
def add(x, y):
    return x + y


@logged(2)
def spam():
    print('Spam!')


print(add(3, 4))
spam()

附录:示例程序输出

35
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
error
no matter
error [Errno 2] No such file or directory: 'test.txt'
no error
no matter
error: division by zero
error: invalid literal for int() with base 10: 'a'
error: hi
1 1 1
1 [1, 2] (1,)
1
1.0
(1+0j)
(1+2j)
(1+2j)
<class 'complex'>
HELLO WORLD
hello world
Hello world
True
True
hello WORLD 
 hello WORLD
hello WORLD
['hello', 'WORLD']
['a', 'b', 'c', 'd']
d
a
one
two
three
['one', 'two', 'three']

one
two
three

['', 'one', 'two', 'three']
1abc2abc3
2
b'1abc2abc3'
1abc2abc3
-str-
str:   str
str:   str, num: 123
Web Server 127.0.0.1:8080
Web Server 127.0.0.1:8080
@@3@@*2&&&&=####6
[3, 2, 4]
[2, 3, 4]
[2, 3, 4, [5, 6]]
[2, 3, 4, [5, 6], 7, 8]
[2, 3, 4, [5, 6], 7, 8, 9, 0]
0
[2, 3, 4, [5, 6], 7, 8, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[2, 4]
[5, 4, 3]
['A', 'B', 'C']
['A', 'B', 'C']
['A', 'B', 'C']
['A', 'B', 'C']
<class 'int'>
<class 'tuple'>
(2, 3, 4, 5, 6)
5
{'abc': 123, 98.6: 37}
{'key': 'value'}
{'a': 1, 'b': 2, 'c': 3}
{'a': [1, 2], 'b': [1, 2], 'c': [1, 2]}
abc
98.6
123
37
123
37
123
37
('abc', 123)
(98.6, 37)
abc 123
98.6 37
{1, 2, 3}
<class 'set'>
{1, 2, 3}
<class 'set'>
{'r', 'd'}
{'a', 'r', 'd'}
{'a', 'r', 'd'}
frozenset({1, 2})
2.1
2
8
1
2
[1, 2, 3, [4, 5]]
['b', 2, 3, [4, 5]]
[1, 2, 3, ['bb', 5]]
['b', 2, 3, ['bb', 5]]
['b', 2, 3, ['bb', 5]]
['b', 2, 3, ['cc', 5]]
str
123
2018-12-12
[1, 2, 3]
(4, 5, 6)
(4, 5, 6)
str
(4, 5, 6)
abc
12
32
abc 12 32
1 2 3
1 2 3
1 2 3
1
(2, 3)
{'a': 1, 'b': 2}
对kwargs拆包
1 2
True
False
True
4438695600 4438695600
False
True
True
True
False
True
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
14
[1, 4, 9, 16, 25, 36, 49, 64, 81]
[4, 16, 36, 64, 100]
['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']
['Java=99', 'C=99', 'C++=99']
<generator object <genexpr> at 0x10bb9ecf0>
1
4
-----
9
16
25
36
49
64
81
fibonacci
<generator object fibonacci at 0x10bb9ed68>
0
1
-----
1
2
3
5
8
13
21
34
0
10.0
15.0
20.0
**********************************
1
Hello World
4
None
9
list_iter
<list_iterator object at 0x10bd1e978>
1
2
str_iter
<str_iterator object at 0x10bd1e978>
1
2
tuple_iter
<tuple_iterator object at 0x10bd1e978>
1
2
set_iter
<set_iterator object at 0x10bd21510>
1
2
dict_iter
<dict_keyiterator object at 0x108bad368>
1
2
[1, 4, 9]
['1', '2', '3', '4', '5', '6', '7', '8', '9']
6
135
[1, 5, 9, 15]
primes
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
[1, 4, 9, 16, 25, 36, 49, 64, 81]
25
(0, 3)
None
matchObj.groups() :  ('Cats', 'smarter')
matchObj.group() :  Cats are smarter than dogs
matchObj.group(1) :  Cats
matchObj.group(2) :  smarter
matchObj.group(1,2) :  ('Cats', 'smarter')
('102300', '')
('1023', '00')
('010', '12345')
('010', '8086')
(0, 3)
(11, 14)
电话号码 :  2004-959-559 
电话号码 :  2004959559
A46G8HFD1134
['123', '456']
['8', '12']
12
32
43
3
['runoob', 'runoob', 'runoob', '']
{'_A__private_attrs': 0, 'attrs': {}}
0
{'_A__private_attrs': 0, 'attrs': {}, 'attr': 'new attr'}
__private_method
new func
new func
be print
{'_A__private_attrs': 0, 'attrs': {'1': 2}, 'attr': 'new attr', 'func': <bound method func of be print>}
2
1
0
123
black dog
white dog
name of an animal
(<class '__main__.A'>, <class '__main__.B'>, <class '__main__.D'>, <class '__main__.C'>, <class '__main__.E'>, <class 'object'>)
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)
B
A
<class '__main__.B'>
<class '__main__.A'>
True
False
<class 'type'>
True
<class '__main__.B'>
True
1
2
3
4
5
static method
static method
class method
1
class method
1
False
False
True
True
fun
begin
fun
end
begin
fun
end
---b---
---a---
---1---
---2---
---c---
---3---
=====
<b><i>hello world</i></b>
<class 'function'>
18
4
4
4
4
4
4
2
3
4
[10, 0]
[10, 20]
[0, 20]
log[priority: 0 , module: add , msg: add x and y ]
7
log[priority: 2 , module: __main__ , msg:  ]
Spam!

Process finished with exit code 0

  • 6
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值