python简单-Python简单教程

python教程

1991年发布第一个版本

设计定位:Python的设计哲学是“优雅”、“明确”、“简单”。

Python开发者的哲学是“用一种方法,最好是只有一种方法来做一件事。

语言分类:脚本语言,NONONO,Python的支持者较喜欢称它为一种高级动态编程语言

Python 2.7将于2020年1月1日终止支持,请使用python3.x

执行Python在执行时,首先会将.py文件中的源代码编译成Python的byte code(字节码),然后再由Python Virtual Machine(Python虚拟机)来执行这些编译好的byte code。

基本数据类型

m_int = 100 # 整数

m_float = 1000.0 # 浮点数,精度与系统相关

m_bytes = b"hello"

m_complex = 2+2.7j # 复数

m_bool = True # 逻辑值, 只有两个值:真、假

m_str = "runoob" # 一个由字符组成的不可更改的有序串行

m_tuple = (4.0, "string", True) #可以包含多种类型的不可改变的有序串行,元组

m_list = [100, "hello", False] # 有序列表,可包含多种数据类型

m_dict = {"key1": 1.0, 3: False} # 一个可改变的由键值对, map

方法,函数

定义方法:def 方法名(参数列表)

def test_fun():

print("hello world")

def fact(n):

if n==1:

return 1

return n * fact(n - 1)

有默认参数的函数

def spam(a, b=42):

print(a, b)

spam(1) # Ok. a=1, b=42

spam(1, 2) # Ok. a=1, b=2

任意数量参数的函数

def avg(first, *rest):

return (first + sum(rest)) / (1 + len(rest))

#接受任意数量的位置参数和关键字参数

def anyargs(*args, **kwargs):

print(args) # A tuple

print(kwargs) # A dict

单个返回值

def test_add(a, b):

return a + b

#调用方法

def test_add(1, 2)

def test_add("hello", "world")

多个返回值

test_move_point(x, y, z):

x += 1

y += 1

z += 1

return x, y, z

#调用函数

a, b, c = test_move_point(1, 2, 3)

返回函数

def lazy_sum(*args):

def temp_sum():

ax = 0

for n in args:

ax = ax + n

return ax

return temp_sum

#调用

f = lazy_sum(1, 2, 3, 4)

f()

匿名函数:lambda关键字

add = lambda: x, y: x + y

add(1, 2)

add("hello", "world")

def square_sum(x, y):

return lambda: x * x + y * y

装饰器,不带参数

import functools

def log(func):

@functools.wraps(func)

def wrapper(*args, **kw):

print "call %s():" % func.__name__

return func(*args, **kw)

return wrapper

@log

def my_func():

print("test my func")

#等价于

myfunc = log(my_func)

带参数的装饰器

import functools

def log(text):

def decorator(func):

@functools.wraps(func)

def wrapper(*args, **kw):

print "%s %s():" % (text, func.__name__)

return func(*args, **kw)

return wrapper

return decorator

装饰器,对象

class Log:

def __init__(self)

类和实例

定义类

class Student:

pass

class Student(object):

pass

创建实例

s = Student()

定义变量和访问限制

class User:

__all_user_count = 0

def __init__(self):

self.name = "Tom"

self.age = 18

self.__money = 100 # 私有变量

User.__all_user_count += 1

def get_money(self):

return self.__money

def set_money(self, m):

self.__money = m

# 私有方法

def __use_money(self):

self.__money -= 1

# 静态方法

@staticmethod

def create_user():

return User()

继承和多态

class Fruits:

def __init__(self):

self.name = "fruits"

def say_hi(self):

print("i am fruits")

class Apple(Fruits):

def say_hi(self):

print("i am apple")

class Pear(Fruits):

def say_hi(self):

print("i am pear")

多重继承

新式类多继承搜索顺序:广度优先

经典类多继承搜索顺序:深度优先

class P(object):

def fun_a(self):

print("function from P")

class A(P):

def __init__(self):

self.name = "b"

def fun_a(self):

print("function from A")

class B(P):

def __init__(self):

self.name = "b"

class C(B, A):

def __init__(self):

A.__init__(self)

B.__init__(self)

获取对象信息

type() 获取对象type

dir() 所有属性和方法

isinstance() 判断是否为某类型或某类型的子类

特殊方法

__init__() 初始化方法,构造方法

__str__() 配合str(object)方法调用

__repr__() 配合repr(object)方法,返回一个可以用来表示对象的可打印字符串

__call__() 对象是否可调用

__len__() 配合len(object)方法调用

文件读写

try:

f = open("D:/test.txt", "r")

f.write("hello world")

finally:

if f:

f.close()

with open("D:/ttt.txt", "w") as f:

f.write("hello world 123")

异常处理

# try...except...else

try:

f = open("D:/test.txt", "w")

f.write("hello sb")

f.close()

except IOError as e:

raise e

else:

print("write file ok")

# try...except...finally

try:

f = open("G:/test.txt", "w")

f.write("hello error")

except IOError as e:

raise e

finally:

if f:

f.close()

线程

调用start_new_thread启动线程

thread.start_new_thread(function, args, kwargs=None)

继承threading.Thread实现run方法

import threading

class ThreadTask(threading.Thread):

def run(self):

print("i am from thread task")

t = ThreadTask()

t.start()

模块和包

模块:一个.py文件就称之为一个模块(Module)

包 :一个目录来组织模块的方法,称为包(Package),每个包下面有个init.py文件,当首次导入这个时会执行该文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值