Python3问题杂记

OpenCV相关

  • 读取目录路径下所有图片:
import os;
import cv2;
def read_image(path): #注意path为此格式 ‘ /imgfoldername ’
	for image_name in os.listdir(path):
		image_path = path+'/'+ image_name;
		print(image_path);
		img = cv2.imread(image_path);
		cv2.imshow("title",img);
		image = cv2.resize(img,(32,32)); # 缩放为32*32
		image = image / 255.0; # 归一化
	

继承

  • 使用类名调用父类**init()**,需要加入self参数;
  • 使用super调用父类**init()**,无需添加self参数;
  • Python 3 可以直接使用 super() 代替 super(Class, self)
  • Python 3 可以不用无需在括号中添加object : class ()
 class Base()def __init__(self):
 		print("Base");
 class A(Base):
 	def __init__(self):
 		super().__init__();
 		print("A");
 class B(Base):
 	def __init__(self):
 		Base.__init__(self);
 		print("B");
a = A();
b = B();

模块

  • 导入其他.py模块后,防止运行所有的代码,可在不必运行代码前加入
if __name__ == "__main__":
  • 使用import导入第三方模块后,若要进行调用其中函数或实例化对象,需要使用模块名.函数/对象名的方式。
import Tools;
	tool = Tools.Tool(); #实例化Tool类
	Tools.say_hello(); #调用say_hello()函数
  • 使用 from … import … 可以按需要导入。

  • 为了避免重名问题 可以使用 as进行重命名,即 import … as

    当使用as进行导入后,无需额外使用模块名的方式调用。

from math import pow;  #从math.py中导入pow()函数
pow(2,3)  # 无需使用math.pow()进行调用
from math import pow as pow_math; #避免与本身pow()函数发生冲突
pow_math(2,3)  # 无需使用math.pow_math()进行调用

列表

  • 常用函数
arr = [1,3,9];
print(len(arr)); # 返回长度
arr.append(3); # 末尾添加3
arr.remove(3); # 删除最近位置的3
print(min(arr),max(arr),sum(arr));
arr.sort(); # 排序
print(arr[:]); # 输出arr
print(arr.count(3)); # 返回3的数目
print(1 not in arr); #判断1是否在arr

字典

  • 常用函数
dic = {"d" : "dad"};
dic["a"] = "apple";
dic["b"] = "boy";
print(dic.keys(),dic.values(),dic.items());#获取所有的index,values
print(dic.get("b")); # 获取索引d的值

字符串

  • 常用函数
str = "hello world!";
p = "l";
print(str.find(p)); # 返回索引或-1
print(len(str)); # 返回长度
print(str[::-1]) # 反转字符串
print(str.split(" ")); # 使用" "划分为list
print(" ".join(str.split(" "))); # 将" "连接为string
print(str.upper()); # 壮大写
print(str.lower()); # 转小写
print(str.capitalize()); # 首字母大写
  • 使用 str.format 格式化
str = "world!";
print("{} ,{}!".format("hi",str)); #默认顺序 
print("{str1},{str2}".format(str2 = str,str1 = 'hi')); #字典方式
print("{0} {1} {0} {2}".format('hello','world','hi')); #指定位置
print("{:.2f}".format(250)); #使用:代替% 输出数字
  • 使用 % 格式化
print("%s age is %d"%("my",15));
  • 使用 + 格式化
str = "hello";
print(str + " world!","my name is python");

函数

  • 形参为函数。
import math;
def math_sum(fun,x):
	print(fun(math.pow(x,2)));
  • 返回值为函数(闭包,即内层函数引用了外层函数的变量(参数也算变量),然后返回内层函数的情况)。
import math;
def math_sum(x,y):
	def sum():
		return x+y;
	return sum;
math_sum(3,4)();  #返回函数需要调用
  • 匿名函数,使用lambda标识。返回值为结果,相当于f(x)=x*x。
 for x in map(lambda x : x*x, list3): 
	print(x);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值