4

python基本语法

 2 years ago
source link: https://blog.51cto.com/u_15488347/5516400
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

python基本语法

原创

阿炳不会扣篮 2022-07-26 19:51:28 ©著作权

文章标签 python基础 文章分类 Python 编程语言 阅读数167

python是一种解释性的脚本语言,解释一行执行一行

依靠缩进来区分代码块( : )

  • del 在内存中删除变量
  • ==dir()==函数可以查看当前变量可以调用那些函数
  • ==eval()==函数可以将字符串当作函数表达式使用
  • 全局变量 ps:global关键字,在函数内部使用外部变量

基本数据结构

  1. 整型 int
  2. 浮点型 float
  3. 布尔型 bool True False

字符型 str str() name="你好呀世界"

name[3] 取出第四个字符

列表 list 数组 [] list()

extends() 拼接值 += 拼接列表一致

append() 直接拼接列表对象,而不是值

元组 tuple ()与列表一致,元素不可改变 tuple()

# 解构赋值 my_tuple = (1, 2, 3) a, b, c = my_tuple print(a, b, c)

字典 dict 键值对 person = { "name": "小明" }

person["name"] 取出字典中的元素

逻辑运算符

  • and 与 类似 &&
  • or 或 类似 |
  • not 非 类似 !

身份运算符

  • isis not判断引用对象是否是同一个
  • ==是判断引用对象的值是否相等

流程控制语句

if 条件:

elif 条件:

else:

  • while 条件:

for 循环变量 in 条件:

else: 循环语句中出现break,不执行

  • 函数定义关键字def
# TODO 一般用来标识自己待做的事情
# python中都是引用传值 id() ==> 查看变量地址
def print_hello(num=19, *args, **dicts):
"""
缺省参数:具有默认值的参数 ==》 num
多值参数:*args接收元组 **kwargs接收字典
"""
return num

person = {
"name": "阿炳"
}

print_hello(num=20, 12,13,14,**person)
  • 对象名一般采用大驼峰法
  • __ 双下划线代表私有
  • ==mro()==方法可以查看方法解析顺序
  • 装饰器
  1. @classmethod 类方法
  2. @staticmethod 静态方法
  • 面向对象三大特性:
  • 单继承
  • 多继承:可以继承多个父类
  • 私有属性和私有方法不被继承
class Father:
skill = "唱歌"

class Mother:
skill = "跳舞"

class Singer(Father, Mother):
name = None # 类属性 一个类只有一个
def __init__(self, salary):
self.salary = salary # 实例属性 每个对象都有
print("构造方法执行")

def __str__(self):
"""
设置对象返回的内容,类似于java中的toString()
:return:
"""
return "你好呀世界"

def __del__(self):
print("对象已经被销毁了")
  • raise: 手动抛异常
  • except:发生异常时执行
  • else: 未发生异常时执行
  • finally: 一定会执行
try:
except 异常类型:
else:
finally:
  1. import 模块名as 别名 导入模块中的全部内容
  2. from ··· import导入模块中指定内容
fp = open("文件名", "操作文件权限", encoding="编码格式")
fp.read() # 读取文件内容
fp.write("内容") # 向文件写内容
fp.close() # 关闭流
with open("文件名", "操作文件权限", encoding="编码格式") as fp:
fp.read() # 读取文件内容
fp.write("内容") # 向文件写内容
fp.close() # 关闭流
操作文件 一个函数三个方法 open read write close open未找到文件自动创建一个
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK