Python基础(持续更新)

1 函数

1.1 函数定义

1)输出字符串“Hello World!":

def hello():
	print("Hello World!")

2)比较两个数,并返回较大的数

def max(a,b):
	if a > b:
		return a
	else:
		return b

1.2 函数调用

hello()

运行结果:

Hello World!

a = 10
b = 20
print(max(a,b))

运行结果:

20

1.3 参数传递

  • 在python中,类型属于对象,对象有不同类型的区分,变量是没有类型的。
  • 在python中,strings, tuples和numbers是不可更改的对象,而list和dict等则是可以修改的对象。

1.3.1 不可变类型

类似C++的值传递,如整数、字符串、元组。传递的只是对象的值,没有影响被传递对象本身。

def swap(a,b):
    z = a
    a = b
    b = z
    
a = 5
b = 10
swap(a, b)
print(a)
print(b)

运行结果:

5
10

1.3.2 可变类型

类似C++的引用传递,如列表、字典。

def changelist(mylist):
    mylist.append([1,2,3,4])   
    return 

mylist=[10,20,30]
changelist(mylist)
print(mylist)

运行结果:

[10,20,30,[1,2,3,4]]

1.4 参数

  • 必须参数
  • 关键字参数
  • 默认参数
  • 不定长参数

1.4.1 必须参数

必须参数须以正确的顺序传入函数,调用时的数量必须和声明时的一样。

def print_str(str):
    print(str)
    return 

print_str("hello")

运行结果:

hello

1.4.2 关键字参数

使用关键字参数允许函数调用时参数的顺序与声明时不一致。

以下实例中函数参数的使用不需要使用指定顺序:

def printInfo(name, age):
	print("名字:", name)
	print("年龄:", age)
	return

printInfo(age = 50, name = "John")

运行结果:

名字: John
年龄: 50

1.4.3 默认参数

调用函数时,如果没有传递参数,则会使用默认参数。

以下实例,如果没有传入age参数,则使用默认值:

def printInfo(name, age=30):
    print("名字:", name)
    print("年龄:", age)
    return

printInfo(name = "John")

运行结果:

名字: John
年龄: 30

1.4.4 不定长参数

1)加了星号 * 的参数会以元组(tuple)的形式导入,存放所有未命名的变量参数。

def printInfo(arg1, *vartuple):
    "打印任何传入的参数"
    print(arg1)
    print(vartuple)
    
printInfo(10, 20, 30)

运行结果:

10
(20, 30)

2)加了两个星号 ** 的参数会以字典的形式导入。

def printInfo(arg1, **vardict):
    "打印任何传入的参数"
    print(arg1)
    print(vardict)
    
printInfo(20, a=5, b=8)

运行结果:

20
{‘a’: 5, ‘b’: 8}

1.5 return语句

return[表达式]语句用于退出函数,选择性地向调用方返回一个表达式。不带参数值的return语句返回None。

2 面向对象

2.1 类定义

1、定义一个Student类

class Student:
    pass

2、类的构造方法:__ init__(),该方法在类实例化时会自动调用。

3、__ init__()可以有参数,参数通过它传递到类的实例化操作上。

class Student:
	# 定义基本属性
	name = ''
	age = 0
	score = 0
	
	# 定义私有属性,在类外部无法直接进行访问
	__weight = 0
	
	# 定义构造方法
    def __init__(self, name, age, score):
        self.name = name
        self.age = age
        self.score = score

# 实例化        
stu = Student("John", 90)

2.2 类的方法

类方法必须包含参数self,且为第一个参数,self代表的是类的实例。

class Person:
    name = ''
    age = 0
    __weight = 0
    
    def __init__(self, name, age, weight):
        self.name = name
        self.age = age
        self.__weight = weight
        
    def printInfo(self):
        print("姓名:", self.name)
        print("年龄:", self.age)

# 实例化
p = Person("John", 18, 80)
p.printInfo()

运行结果:

姓名: John
年龄: 18

2.3 继承

继承Person类:

class Student(Person):
    score = 0
    def __init__(self, name, age, weight, score):
        #调用父类的构造函数
        Person.__init__(self, name, age, weight)
        self.score = score
        
    # 覆盖父类的方法
    def printInfo(self):
        print("姓名:", self.name)
        print("年龄:", self.age)
        print("分数:", self.score)
        
stu = Student('Ken', 20, 75, 90)
stu.printInfo()

运行结果:

姓名: Ken
年龄: 20
分数: 90

2.4 方法重写

如果父类方法的功能不能满足要求,可以在子类中重写父类的方法,上面子类Student重写了父类Person的方法printInfo()。

3 模块

一个python文件主要有两种使用方法:

1. 作为脚本直接执行
如果作为脚本直接执行,if __ name__ == “__ main__”:语句之前和之后的代码都被执行。

2. import到其他python脚本中被调用
如果import执行,if __ name__ == “__ main__”:语句之前的代码被执行,而之后的代码没有被执行。

4 日期和时间

获取格式化日期和时间的两种方式:
1、通过time模块

import time

print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

运行结果:

2022-12-29 16:15:25

2、通过datetime模块

from datetime import datetime

print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

运行结果:

2022-12-29 16:14:56

5 文件

1、mode = ‘w’,以写入模式打开文件

# 以w写入模式,创建test.txt
file = open('./test.txt', mode = 'w')

# 写入内容
file.write('hello\n')
file.write('world\n')

# 关闭文件
file.close()

文本内容为:

hello
world

2、mode = ‘a’,以追加内容模式打开文件

file = open('./test.txt', mode = 'a')
file.write('hello world\n')
file.close()

文本内容为:

hello
world
hello world

3、mode = ‘r’,以只读模式打开文件

file = open('./test.txt', mode = 'r')

读取一行内容:

str = file.readline()
print(str)
str = file.readline()
print(str)
str = file.readline()
print(str)
file.close()

运行结果:

hello
world
hello world

6 多线程

Python3线程中常用的两个模块为:

  • _thread
  • threading(推荐使用)

6.1 使用_thread模块创建线程

调用_thread模块中的start_new_thread()函数来产生新线程:

import _thread
import time

# 为线程定义一个函数
def print_time(threadName, delay):
    count = 0
    while count < 5:
        time.sleep(delay)
        count += 1
        print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ' ' + threadName + '\n')

        
# 创建两个线程
try:
    _thread.start_new_thread(print_time, ("Thread - 1", 2, ))
    _thread.start_new_thread(print_time, ("Thread - 2", 4, ))
except:
    print("Error:无法启动线程")

运行结果:

2022-12-29 17:45:43 Thread - 1
2022-12-29 17:45:45 Thread - 2
2022-12-29 17:45:45 Thread - 1
2022-12-29 17:45:47 Thread - 1
2022-12-29 17:45:49 Thread - 2
2022-12-29 17:45:49 Thread - 1
2022-12-29 17:45:51 Thread - 1
2022-12-29 17:45:53 Thread - 2
2022-12-29 17:45:57 Thread - 2
2022-12-29 17:46:01 Thread - 2

6.2 使用threading模块创建线程

import threading
import time

exitFlag = 0

class myThread(threading.Thread):
    def __init__(self, threadID, name, delay):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.delay = delay
        
    def run(self):
        print("开始线程:" + self.name)
        print_time(self.name, self.delay, 5)
        print("退出线程:" + self.name)
        
def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            threadName.exit()
        time.sleep(delay)
        print(threadName + time.strftime(" %Y-%m-%d %H:%M:%S", time.localtime()) + '\n')
        counter -= 1
        
thread1 = myThread(1, "Thread-1", 2)
thread2 = myThread(2, "Thread-2", 4)

thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("退出主线程")

运行结果:

开始线程:Thread-1
开始线程:Thread-2
Thread-1 2022-12-30 09:05:35
Thread-2 2022-12-30 09:05:37
Thread-1 2022-12-30 09:05:37
Thread-1 2022-12-30 09:05:39
Thread-2 2022-12-30 09:05:41
Thread-1 2022-12-30 09:05:41
Thread-1 2022-12-30 09:05:43
退出线程:Thread-1
Thread-2 2022-12-30 09:05:45
Thread-2 2022-12-30 09:05:49
Thread-2 2022-12-30 09:05:53
退出线程:Thread-2
退出主线程

猜你喜欢

转载自blog.csdn.net/Kigha/article/details/128478397