python学习

Python学习笔记

本文是基于以下的系统环境,学习和测试Python:

  • Windows 10
  • PyCharm

一、Python语言学习

(1)创建类和对象

  • 创建一个猫类
class Cat(object):
	# 类属性,类似于static int num = 0,该变量属于整个类,被所有的实例对象共享 
	# 类的静态变量
	num = 0  
	# 实例属性定义,并非类属性
    def __init__(self, name, color):
        self.name = name  # 公有属性  
        self.__color = color # 私有属性
    # 实例的方法定义
    def __str__(self):
        return "name:" + self.name + ",color:" + self.__color
    def __del__(self):
    	print(self.name + 'is deleted.')
    def setColor(self, color):
    	self.__color = color
    def getColor(self):
    	return self.__color
    # __eat() 为私有方法
    def __eat(self):
        print('eating...')
    def printInfo(self):
        print(self.name, 'is', self.__color)
    # 类方法,只能对类属性进行操作和修改
    @classmethod
    def setNum(cls, num):
    	cls.num = num
    # 静态方法
    @staticmethod
    def printTest():
    	print('test...')

if __name__ == '__main__':
    cat = Cat('Tom', 'blue') # 创建一个猫对象
    cat.printInfo()
    print(Cat.num) # 用类去访问类属性
    # 也要用类去改变类属性的值,如果使用对象去改变值
    # 如 cat.num=100,不会修改类属性num的值,而是会增加一个实例属性num
    Cat.num = 10 
    print(cat)
    print(cat.name) # 运行访问
    # print(cat.__color) # 不允许访问
    del cat # 删除cat对象
  • 如何调用私有方法
class Cat(object):
    # 实例属性定义,并非类属性
    def __init__(self, name, color):
        self.name = name  # 公有属性
        self.__color = color # 私有属性
    # 类的方法定义
    def __str__(self):
        return "name:" + self.name + ",color:" + self.__color
    def __del__(self):
        print(self.name + 'is deleted.')
    def setColor(self, color):
        self.__color = color
    def getColor(self):
        return self.__color
    # __eat() 为私有方法
    def __eat(self):
        print('eating...')
    def printInfo(self):
        print(self.name, 'is', self.__color)
if __name__ == '__main__':
    cat = Cat('Tom', 'blue')  # 创建一个猫对象
    cat.printInfo()
    print(cat)
    print(cat.name)  # 运行访问
    # print(cat.__color) # 不允许访问
    print(dir(Cat)) # 通过dir(Cat)来查询该类所有的方法
    cat._Cat__eat() # 调用私有的__eat()方法
    del cat  # 删除cat对象

(2)继承

  • 单继承
class Cat(object):
    def run(self):
        print('runing...')
class Bosi(Cat):
	pass

if __name__ == '__main__':
    bosi = Bosi() # 创建一个波斯猫对象
    bosi.run()
  • 多继承
class A(object):
    def printA(self):
        print('----A----')
class B(object):
    def printB(self):
        print('----B----')
class C(A, B):
    def printC(self):
        print('----C----')
if __name__ == '__main__':
    c = C()
    c.printA()
    c.printB()
    c.printC()
  • 多继承优先继承第一个
class A(object):
    def run(self):
        print('----A----')
class B(object):
    def run(self):
        print('----B----')
class C(A, B):
    pass
if __name__ == '__main__':
    c = C()
    c.run()
# 输出结果
# ----B----
print(C.__mro__) # 输出该类中方法的调用的类顺序

(3)多态

  • 单继承
class A(object):
    def run(self):
        print('----A----')
class B(object):
    def run(self):
        print('----B----')
class C(A, B):
    def run(self):
        print('----C----')
if __name__ == '__main__':
    c = C()
    c.run()
# 输出 ----C----
	c = B()
    c.run()
# 输出 ----B----
	c = A()
    c.run()
# 输出 ----A----

(4)print格式化输出

name = 'Tom'
color = 'blue'
age = 3
print('%s is %s, and %d years old.' % (name, color, age))
# Tom is blue, and 3 years old.
#     符 号	 描 述
#      %c	 格式化字符及其ASCII码
#      %s	 格式化字符串
#      %d	 格式化整数
#      %u	 格式化无符号整型
#      %o	 格式化无符号八进制数
#      %x	 格式化无符号十六进制数
#      %X	 格式化无符号十六进制数(大写)
#      %f	 格式化浮点数字,可指定小数点后的精度
#      %e	 用科学计数法格式化浮点数
#      %E	 作用同%e,用科学计数法格式化浮点数
#      %g	 %f和%e的简写
#      %G	 %f 和 %E 的简写
#      %p	 用十六进制数格式化变量的地址

Python 3 print 函数用法总结

(3)异常

  • 捕获多个异常
try:
	print(abc)
	open("text.txt")
exception (NameError, FileNotFoundError) as e:
	print("捕获一个异常")
	print(e)
  • 捕获所有异常
try:
	print(abc)
	open("text.txt")
except Exception as e:
	print("捕获一个异常")
	print(e)
  • 没有捕获到异常的处理办法
try:
	print(abc)
	open("text.txt")
except Exception as e:
	print("捕获一个异常")
	print(e)
elseprint("没有捕获异常")
  • 不管有没有捕获到异常,都要执行的语句
try:
	print(abc)
	f = file("text.txt")
except Exception as e:
	print("捕获一个异常")
	print(e)
elseprint("没有捕获异常")
finallyprint("一定要执行的语句")
	f.close()
  • 自定义异常
class ShortInputException(Exception):
	def __init__(self, length, atleast):
		self.length = length
		self.atleast = atleast
	def __str__(self):
		print('ShortInputException:输入长度为%d,长度至少为%d'%(self.length,self.atleast))
try:
	s = input('请输入')
	if len(s)<3:
		raise ShortInputException(len(s), 3)
except EOFError:
	print('您输入一个结束符标记EOF')
except ShortInputException as e:
	print(e)
else:
	print("没有捕获异常")

二、Python常用方法

(1)判断字典dict在key是否存在

dict = {'name':'z','Age':7,'class':'First'};
print("Value : ",dict3.__contains__('name'))
print("Value : ",dict3.__contains__('sex'))

(2)str字符串转布尔类型

mode = str(configure.get('debug', 'mode')).lower() == 'true'

(3)去除字符串空格

  • 1. 去除字符串开头或者结尾的空格
myStr = " aa aaa "
myStr.strip()
# 也可以去除指定的字符
myStr = ",aa aaa ,"
myStr.strip(',')
  • 2. 去除字符串开头的空格
myStr = " aa aaa "
myStr.lstrip()
  • 3. 去除字符串结尾的空格
myStr = " aa aaa "
myStr.rstrip()

(4)替换字符串中指定的字符

myStr = " aa aaa "
myStr.replace(" ", "")

(5)以指定字符分割字符串

myStr = "aa,bb,cc"
myStr = myStr.split(',')
# myStr = ['aa', 'bb', 'cc']

三、Python的相关命令

(1)python

  • 制作自己的模块
python setup.py sdist
  • 创建__init__.py文件,并键入以下内容
__all__ = ["characteristic_value"]
  • 创建setup.py文件,并键入以下内容
from distutils.core import  setup
setup(name='characteristic_value', version='1.0', author='xuzheng', py_modules=['CV.characteristic_value'])

(2)pip

  • pip更新
pip install -U pip --user
  • pip安装网络上的第三方的包
pip install somepackage
  • pip安装本地的第三方的包
pip install ..\module_test\dist\mytest.tar.gz
  • pip卸载第三方的包
pip uninstall somepackage
  • 列出已安装的包
pip list

(3)读取配置文件ini

  • pip安装网络上的第三方的包configparser
pip install configparser
# 配置文件configure.ini
[network]
host=172.30.12.188
port=5003
# 读取网络配置参数
config = configparser.ConfigParser()
config.read("config/configure.ini")
host = config.get('network', 'host')
port = config.get('network', 'port')
print(host)  # 172.30.12.188
print(port)  # 5003

四、PyCharm

(1)添加作者信息

  • 打开pycharm,点击File
  • 点击Settings
  • 点击Editor
  • 点击Code Style
  • 点击File and Code Templates
  • 点击Python Script
    在这里插入图片描述
  • 键入以下内容
# -*- coding: utf-8 -*-
"""
@File    : ${NAME}.py
@Project : ${PROJECT_NAME}
@Software: ${PRODUCT_NAME}
@Time    : ${DATE} ${TIME}
@Author  : xuzheng
@Email   : 601797071@qq.com
@Description: 
"""

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值