Python 编程中的一些常用知识点

1. 如何在一个.py文件中调用另一个.py文件的类

#mymodel.py

import matplotlib.pyplot as plt
class test(object):
num = []

def __init__(self, _list):
super(test, self).__init__()
self.num = _list

def prt(self):
print(self.num)

def tplt(self):
plt.plot(self.num)
plt.show()

#mian.py

from mymodel import test
mylist= [1,2,3]
a = test(mylist)
a.prt()
a.tplt()

转载:https://www.cnblogs.com/wqpkita/p/7124930.html

2.变量的命名规范

模块名: 
小写字母,单词之间用_分割 
ad_stats.py 

包名: 
和模块名一样 

类名: 
单词首字母大写 
AdStats 
ConfigUtil 

全局变量名(类变量,在java中相当于static变量): 
大写字母,单词之间用_分割 
NUMBER 
COLOR_WRITE 

普通变量: 
小写字母,单词之间用_分割 
this_is_a_var 

实例变量: 
以_开头,其他和普通变量一样 
_price    
_instance_var 

私有实例变量(外部访问会报错): 
以__开头(2个下划线),其他和普通变量一样 
__private_var 

专有变量: 
__开头,__结尾,一般为python的自有变量,不要以这种方式命名 
__doc__ 
__class__ 

普通函数: 
和普通变量一样: 
get_name() 
count_number() 
ad_stat() 

私有函数(外部访问会报错): 
以__开头(2个下划线),其他和普通函数一样 
__get_name() 
————————————————————————————————————————————————————————————————————
文件名 
全小写,可使用下划线 
包 
应该是简短的、小写的名字。如果下划线可以改善可读性可以加入。如mypackage。 
模块 
与包的规范同。如mymodule。 
类 
总是使用首字母大写单词串。如MyClass。内部类可以使用额外的前导下划线

转载自:https://www.cnblogs.com/Maker-Liu/p/5528213.html

3.使用Logging 模块记录Log

Python中有一个模块logging,可以直接记录日志

#   日志级别
# CRITICAL 50
# ERROR    40
# WARNING  30
# INFO     20
# DEBUG    10

logging.basicConfig()函数中的具体参数:
filename:   指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中;
filemode:   文件打开方式,在指定了filename时使用这个参数,默认值为“w”还可指定为“a”;
format:      指定handler使用的日志显示格式;
datefmt:    指定日期时间格式。,格式参考strftime时间格式化(下文)
level:        设置rootlogger的日志级别
stream:     用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。
                  若同时列出了filename和stream两个参数,则stream参数会被忽略。

3.1 打印日志到标准输出中

import logging
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')

 输出结果

C:\Users\Administrator\AppData\Local\Programs\Python\Python36\python.exe D:/pyworkpeace/tupian.py 'https://www.tianyancha.com/login'
WARNING:root:warning message

Process finished with exit code 0

可以看出默认情况下Python的logging模块将日志打印到了标准输出中,且只显示了大于等于WARNING级别的日志。默认的日志的格式为:

日志级别:Logger名称:用户输出消息

3.2 将日志文件输入到文件中

import os
logging.basicConfig(filename=os.path.join(os.getcwd(),'log.txt'),level=logging.DEBUG)
logging.debug('this is a message')

运行这三行代码后会在安装Python的目录中出现一个log.txt文件,文件内容

DEBUG:root:this is a message
DEBUG:root:debug message

转载自:https://www.cnblogs.com/bethansy/p/7716747.html

4. Python 时间日期格式化输出

import time

print(time.time())  #输出的是时间戳
print(time.localtime(time.time()))   #作用是格式化时间戳为本地的时间
print(time.strftime('%Y-%m-%d')

参考:

%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
%B 本地完整的月份名称
%c 本地相应的日期表示和时间表示
%j 年内的一天(001-366)
%p 本地A.M.或P.M.的等价符
%U 一年中的星期数(00-53)星期天为星期的开始
%w 星期(0-6),星期天为星期的开始
%W 一年中的星期数(00-53)星期一为星期的开始
%x 本地相应的日期表示
%X 本地相应的时间表示
%Z 当前时区的名称
%% %号本身 
 

5.格式化输出(format 和 %)

%o —— oct 八进制
%d —— dec 十进制
%x —— hex 十六进制

%f ——保留小数点后面六位有效数字
  %.3f,保留3位小数位
%e ——保留小数点后面六位有效数字,指数形式输出
  %.3e,保留3位小数位,使用科学计数法
%g ——在保证六位有效数字的前提下,使用小数方式,否则使用科学计数法
  %.3g,保留3位有效数字,使用小数或科学计数法

%s
%10s——右对齐,占位符10位
%-10s——左对齐,占位符10位
%.2s——截取2位字符串
%10.2s——10位占位符,截取两位字符串

 1 >>> print('{} {}'.format('hello','world'))  # 不带字段
 2 hello world
 3 >>> print('{0} {1}'.format('hello','world'))  # 带数字编号
 4 hello world
 5 >>> print('{0} {1} {0}'.format('hello','world'))  # 打乱顺序
 6 hello world hello
 7 >>> print('{1} {1} {0}'.format('hello','world'))
 8 world world hello
 9 >>> print('{a} {tom} {a}'.format(tom='hello',a='world'))  # 带关键字

转载自:https://www.cnblogs.com/fat39/p/7159881.html

6. Python 对字符串的操作

https://www.cnblogs.com/printN/p/6924077.html

7. Python 输出带颜色的字体

print('\033[1;35;0m字体变色,但无背景色 \033[0m')  # 有高亮 或者 print('\033[1;35m字体有色,但无背景色 \033[0m')
print('\033[1;45m 字体不变色,有背景色 \033[0m')  # 有高亮
print('\033[1;35;46m 字体有色,且有背景色 \033[0m')  # 有高亮
print('\033[0;35;46m 字体有色,且有背景色 \033[0m')  # 无高亮

转载自: https://www.cnblogs.com/daofaziran/p/9015284.html

7. Python 中Str的 find() 的用法

abc = "qwertyuiopqwertyuiop"

if abc.find('abc'):#判断是否包含yui字符串

  print("Yes")

else:

  print("No")

你会发现结果还是:

这是因为find()若找不到对应字符串则返回-1

正确的判断语句应该是:

if abc.find("abc") != -1

...

...

而且find()若找到对应字符串返回的也不是1,那是什么呢? 之前有提到,返回的是查询字符串在被查询字符串中第一次出现的位置


举个栗子:

abc = 'qwertyuiopqwertyuiop'

print(abc.find('yui'))

结果:

打印的是y在字符串‘qwertyuiopqwertyuiop’中第一次出现的位置,注意python从0开始

转载自:https://www.cnblogs.com/hwd9654/p/5682217.html

8. Python调用Linux命令

import os  

os.system("echo \"Hello World\"")   # 直接使用os.system调用一个echo命令  

Hello World         ——————> 打印命令结果  

0                         ——————>What's this ? 返回值

转载自:https://www.cnblogs.com/hujq1029/p/7096247.html

9. Python的高效编程19个技巧

https://www.cnblogs.com/rourou1/p/6148483.html

10. Python读取配置文件Config

cf = configparser.ConfigParser()

cf.read(config.ini)

cf.get("config", name)

cf.set("config", name, value)

配置文件中的名字是不区分大小写的

转载自:https://blog.csdn.net/hey_man2017/article/details/79980272

11.Python Try except finally的用法

如果try中没有异常,那么except部分将跳过,执行else中的语句。

finally是无论是否有异常,最后都要做的一些事情

转载自:https://blog.csdn.net/u010009033/article/details/81840923

猜你喜欢

转载自blog.csdn.net/guyan1101/article/details/93735035