python(入门、进阶)

2020-10-06  本文已影响0人  royluck

记:2020-10-06

==》python基本数据类型:
python基本数据类型

------> 数字:

9 // 4 // 取整,2
9%4 // 取余, 1
9 /3 // 3.0 除数返回默认为double float类型
bool('') // 0
bool([]) // False
bool({}) // False
bool(()) // False
bool(None) // False
0b10 // 2
0x 10 // 16
0o 10 // 8
bin(10) // 0b1010
int(0b10) // 2
oct(10) // 0o12
hex(10) // 0xa

------> 字符串:

'字符串' + '拼接' // '字符串拼接'
'字符串取值'[-1] // '值'
'字符串取值'[3:] // '取值'
'''字符串换行''' // '字符串换行'
 r'字符串特殊字符,不让其转义,如文件地址 D:\xampp' //  '字符串特殊字符,不让其转义,如文件地址 D:\\xampp'
R'C:\Windows' // 'C:\\Windows'
'字符串乘数'*2 // '字符串乘数字符串乘数'
"hellow world"[0:8:2] // 'hlo '

------> set:

{1,2,3} - {2} // {1,3} 求差
{1,2,3} & {2} // {2} 交集
{1,2,3} | {2} // {1,2,3} 并集
A={1,2,3,4,5,6} 
A.add(7) 
print(A) // {1,2,3,4,5,6,7}
A={1,2,3,4,5,6} 
A.discard(6)
print(A)  // {1,2,3,4,5}

------> tuple:


------> 常用方法:
in、 not in、 ord、chr

3 in {1,2,3} // True
3 not in (1,2,3) // False
ord('w')  // 119 返回对应字符的ascii码
chr(119) // 'w'

------> 字典:

 type({}) // <class 'dict'>

注: 有时候会觉得字典跟我们js的对象有点傻傻分不清,js的对象可以通过obj.name或者obj['name']访问;而python的字典只能通过dict['name']访问,实例只能通过obj.name访问。


------> 杂:

if condition
  a 
else
  b  
==>  a or b
def function(arg,*args,**kwargs):
    print(arg,args,kwargs)

function(6,7,8,9,a=1, b=2, c=3) // 6 (7, 8, 9) {'a': 1, 'b': 2, 'c': 3}

==》python运算符:

------> 算数运算符:
+ - * / // % **

2**2 // 4 (2的2次方)  

------> 赋值预算符:
== += -= /= %= **= //=

------> 比较(关系)运算符:
== != > < >= <=

------> 逻辑运算符:
and or not

------> 成员运算符:
in not in

------> 身份运算符:
is is not

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

------> 位运算符:
(把数字当作二进制进行运算)

& | ^ ~ << >>

------> 运算符优先级:

image.png
==》Python项目的组织结构:

包 模块 类 函数、变量

使用import module_name 后面只能跟模块名(即文件名);
import 只能导入模块,不能直接导入模块下的变量;

import p.m as m
print(m.a) # a是模块下的变量

import的缺点是命名空间太长;
import 不能使用相对路径;

form import 可以直接导入具体的变量和函数,也可以导入具体的模块;
from p.m import * # 建议少星号

import sys
print(dir(sys)) # 可以传入指定的模块或类

==》函数:
// js:
let arr = [1,2,3,4]
[a,b] = arr // a = 1, b = 2
[a, ...b] = arr // a = 1, b = [2,3,4]

#python
a,b = [1,2,3,4] # 报错
a,*b = [1,2,3,4] # a = 1,b = [2,3,4] 这里的解包,右边数据类型无论是元祖、集合、还是列表,解包回来的b都是列表(list)类型
def add(x, y)
  pass
c = add(y = 1, x = 2)
def add(x = 1,  y = 2) 
  pass
def add(x,y = 6, z = 8):
  pass
add(10,y = 10, 2) # 报错 argument
def demo(*param):
  print(param)
  print(type(param)) # tuple 无论实参是list,还是tuple、set,这里都是tuple类型

a = [1,2,3]
demo(*a)
def demo(param1, param2 = 3, *param):
  print(param)
  print(type(param))
def city_temp(**param):
  print(param)
  print(type(param))
for key,value in param.items():
  print(key,value)
def demo():
  c=10
  for i in range(0,20):
    a = 10
    c += i
  print(c) # 200
  print(a) # 10

demo()

-> global 关键字:
(python中,所属函数可以访问全局变量,但是不建议所属函数修改全局变量,如下所示)

c = 10
def demo():
  global c
  c = 2
demo()
print(c) # 2

==》类(面向对象):
class Student():
  age = 10
  def print_age(self):
    print(self.age)
def __init__(self)  # 必须带self
    pass

-> 构造函数不能强制返回其他类型,必须(默认None)None,否则报错;

def __init__(self) 
    return 666 # 会报错

-> Student.__init__()

class Student():
  name = ''
  age = 0
  def __init__(self,name,age):
    self.name = name 
    self.age = age
@classmethod
def do_work(cls):
  pass
@staticmethod
def add(a,b):
  pass

-> 静态方法不用像实例方法一样强制传递self和cls参数
-> 对象和类都可以调用静态方法
-> 静态方法可以访问类变量

super(Student,self). __init__(name,age)
super(Student,self). do_homework()

==》枚举:

Python中枚举的用法

print(VIP.YELLOW) # VIP.YELLOW
print(VIP.YELLOW.value)
print(VIP.YELLOW.name)
print(VIP["GREEN"])
from enum import Enum
class VIP(Enum):
    YELLOW = 1
    GREEN = 2
    BLUE = 1

print(VIP.YELLOW) # VIP.YELLOW
print(VIP.BLUE) #  VIP.YELLOW
print(VIP['BLUE']) # VIP.YELLOW


for v in VIP:
  print(v) 
#打印结果:
# VIP.YELLOW
# VIP.GREEN

for v in VIP.__members__.items():
  print(v)
# 打印结果:
# ('YELLOW', <VIP.YELLOW: 1>)
# ('GREEN', <VIP.GREEN: 2>)
# ('BLUE', <VIP.YELLOW: 1>)

for v in VIP.__members__:
  print(v)
# 打印结果:
# YELLOW
# GREEN
# BLUE
a = 1
VIP(a) # VIP.YELLOW
from enum import IntEnum,unique
@unqiue
class VIP(IntEnum):
  YELLOW = 1
  GREEN = 1 # 报错
  BLUE = 'str' # 报错

==>函数式编程(闭包)

python一切皆对象

def curve_pre():
  a = 10
  def curve(x):
    return a*x
  return curve

f = curve_pre()
f(2)
f.__closure__
f.__closure__[0].cell_contents
def f1():
  a = 10
  def f2()
    a = 8 #python没有认为是一个局部变量(没用引用外部啊= 10)
  return f2

f = f1()
origin = 0
def factory(pos):
  def go(step):
    nolocal pos #声明非本地pos局部变量
    new_pos= pos+step
    origin = new_pos # 否则python会认为等号左边的origin是一个局部变量声明
    return new_pos
  return go

tourist = factory(origin)

==>匿名函数(lambda):
def add(x,y):
  return x + y
# 等同于
lambda x,y: x+y

==>三元表达式:
x > y ? x: y
#等同于
x if x > y else y # 格式:条件为真时返回的结果 if 条件判断 else 条件为假时的返回结果

==> map、reduce、filter
list1 = [1,2,3]
list2 = [1,2,3]
def square(x):
  return x * x
r = map(square, list1)
print(list(r)) # 需要转换为list格式
# 等同于
map(lambda x,y: x + y, list1, list2)

#导入reduce
from functools import reduce

r = filter(lambda x: x>1, list1)


import time

def decorator(func):
    def wrapper():
        print(time.time())
        func()
    return wrapper

def f2():
    print('this is a function')

f = decorator(f2)
f()

# 语法糖
# 装饰器最大的用处(相比上面)

@decorator
def f1():
    print('this is a function')

f1()

--> 改造:支持多个参数(上述不能传参)

def decorator(func):
    def wrapper(*args):
        print(time.time())
        func(*args)
    return wrapper

@decorator
def f2(param1, param2):
    print(f'this is {param1}')
    print(f'this is {param2}')

f2('roy', 'roben')

--> 再次优化:

def decorator(func):
    def wrapper(*args,**kw):
        print(time.time())
        func(*args,**kw)
    return wrapper
@decorator
def f2(param1, param2, **kw):
    print(f'this is {param1}')
    print(f'this is {param2}')
    print(kw) # {'a': 1, 'b': 2}

f2('roy', 'roben', a = 1, b =2)

==>字典映射代替switch case语句:
day = 0

def get_sunday():
    return 'Sunday'

def get_monday():
    return 'Monday'

def get_tuesday():
    return 'Tuesday'

def get_default():
    return 'Unknow'

switch = {
    0: get_sunday,
    1: get_monday,
    2: get_tuesday,
}

r = switch.get(day, get_default)() # get方法具有容错性
print('日期:')
print(r)

==>列表推导式:
list = (1,2,3)
list_new = [i**2 for i in list]
print(list_new)
list_new = {i**2 for i in list if i > 1} # 加条件
print(list_new)
list_new = (i**2 for i in list if i > 1)
print(list_new) #返回迭代器
print(*list_new)
# 打印结果:
# [1, 4, 9]
# {9, 4}
# <generator object <genexpr> at 0x0000021EF894D148>
# 4 9

# list_new:generator object
for i in list_new:
  print(i) # 4 9


students = {
    'roy': 18,
    'roben': 20,
}

b = { value: key for key,value in students.items()}
print(b)
# 打印结果:
# {18: 'roy', 20: 'roben'}
==>可迭代对象 迭代器(interator)(针对对象来说):
class bookCollection:
    def __init__(self):
        self.data = ['data1', 'data2', 'data3']
        self.cur = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.cur >= len(self.data):
            raise StopIteration()
        r = self.data[self.cur]
        self.cur += 1
        return r

books = bookCollection()
import copy
books_copy = copy.copy(books) # 浅拷贝 deepcopy 深拷贝
# 迭代器只有一次性
for i in books_copy:
    print(i)

# 迭代器可以调用next方法,但是迭代对象不可以调用next方法
books1 = bookCollection()
print(next(books1))

==> 生成器(针对函数来说)
def gen(max):
    n = 0
    while n<=max:
        n+=1
        yield n

# 解决了内存问题
g = gen(100)
print(next(g))
print(next(g))
print(next(g))

# 生成器
g1 = (i for i in range(0, 100))

==> 非空判断:
# 判空操作
a = None # False 0 '' []
if a:
    pass

if not a:
    pass

# 不建议用下面进行判空
if a is None:
    pass

==>对象存在不一定是True:
class Test():
    def __len__(self):
        return 0 # 只能返回整型数字 或者 True False

    def __bool__(self):
        return False # 只能True False

==>装饰器的副作用:
from functools import wraps
def decorator(func):
    @wraps(func)
    def wrapper(*args):
        print(time.time())
        func(*args)
    return wrapper

==>walrus operator 海象运算符 (必须python 3.8版本以上)
a = 'python'

if (b:=len(a)) > 5:
    print('长度大于5:'+ '真实长度为' + str(b))

==> dataclass(语法糖)
from dataclasses import dataclass

@dataclass
class A():
    name: str
    postion: float

a = A('roy', 1.2)
print(a__repr__()) # A(name='roy', postion=1.2)
print(a) # A(name='roy', postion=1.2)
@dataclass(init=False, repr = False)
上一篇 下一篇

猜你喜欢

热点阅读