python基础语法

1.输入框

a = input("input:")
print("你刚刚输入的是:%s"%a)

2.数学运算

## 习惯性的计算
b=5
c=2
b+c
b-c
print(b*c) ##  相乘 10
print(b/c) ## 想除,与其他语言不同的是,这个可以得出小数2.5
print(b//c) ## 相除取整 2
print(b%c)  ## 相除取余数 1
print(b**c) ## 幂 25
## 表达式计算
d=input("input:")
e=eval(d)
e # input:7+8-4 # 11

3.判断执行

f=2
if f>=18:
    print("你已经成年了")
else:
    print("未成年")
print('-------if的几种情况-----------')
## ""  None 0 [] {} 都为假
## 非0为真
if not "":
    print('为假')
if not None:
    print('为假')
if not 0:
    print('为假')
if not []:
    print('为假')
if not {}:
    print('为假') 
if  1:
    print('为真')
if  -1:
    print('为真')
if  'a':
    print('为真')

结果

未成年
-------if的几种情况-----------
为假
为假
为假
为假
为假
为真
为真
为真

4.while循环执行

g=1

while g<10:
    print(g)
    g=g+1

结果

1
2
3
4
5
6
7
8
9

九九乘法表

i = 1
while i <= 9 :
    j = 1
    while j <= i :
        print("%d*%d=%d\t" % (j,i,i*j),end="")
        j += 1
    i += 1
    #print("\n",end="")
    print("")

结果

1*1=1    
1*2=2    2*2=4   
1*3=3    2*3=6   3*3=9   
1*4=4    2*4=8   3*4=12  4*4=16  
1*5=5    2*5=10  3*5=15  4*5=20  5*5=25  
1*6=6    2*6=12  3*6=18  4*6=24  5*6=30  6*6=36  
1*7=7    2*7=14  3*7=21  4*7=28  5*7=35  6*7=42  7*7=49  
1*8=8    2*8=16  3*8=24  4*8=32  5*8=40  6*8=48  7*8=56  8*8=64  
1*9=9    2*9=18  3*9=27  4*9=36  5*9=45  6*9=54  7*9=63  8*9=72  9*9=81

扫一扫欢迎关注,一起学习!
python基础语法_第1张图片

5.for循环

print('---------for用法--------------')
k='wangbo'
l=''
for x in k:
    print(x)
print('---------for-else用法--------------')
for x in l:
    print(x)
else:
    print("没有数据")
print('---------break用法--------------')    
for x in k:
    if x=='n':
        break
    print(x)
print('----------continue用法-------------')    
for x in k:
    if x=='n':
        continue
    print(x)

结果

---------for用法--------------
w
a
n
g
b
o
---------for-else用法--------------
没有数据
---------break用法--------------
w
a
----------continue用法1-------------
w
a
g
b
o

6.字符串操作(结果在注释后面)

## len函数返回对象的长度或者个数
  m1='wangbo'
  len(m1) ## 结果6
  m2=[1,2,3,4,5,6,7,8]
  len(m2) ## 结果8
  m3=(1,2,'a','5')
  len(m3) ## 结果4
  m4={'name':'wangbo','age':25}
  len(m4) ## 结果2
 
 ## 通过下标取出部分字符
 '''
 [:] 提取从开头(默认位置0)到结尾(默认位置-1)的整个字符串
 [start:] 从start 提取到结尾
 [:end] 从开头提取到end - 1
 [start:end] 从start 提取到end - 1
 [start:end:step] 从start 提取到end - 1,每step 个字符提取一个
 [::-1]逆序
 '''
 m5='wangbo'
 m5[0]
 m5[1]
 m5[2] ## 输出结果 w a n (如果超出下标会报错)
   ## 从右边取字符串
 m5[-1] ## '0'
 
 ## 切片 切片是指对操作的对象截取其中一部分的操作
 m5[0:4] # 取 下标0~3 的字符:wang
 m5[4:] # 取 下标为4开始到最后的字符:bo
 m5[1:-1] # 取 下标为1开始 到 最后第2个  之间的字符:angb
 
 ## 逆序(倒序)
 m5[::-1] # obgnaw
 
 ## find  rfind
 m6='hello wang bo and wang'
 m6.find('wang') # 在字符串中查找 字符串首次出现的位置 如果不存在就返回 -1
 m6.find('o',6,len(m6)) # 指定查找区域
 m6.rfind('bo') # 类似于 find()函数,不过是从右边开始查找
 
 ## index index()跟find()方法一样,只不过如果str不在 mystr中会报一个异常
 ## rindex 同理
 m6.index('wang')
 
 ## replace 把 str1 替换成 str2,如果 count 指定,则替换不超过 count 次,最多等于count
 ## 函数:replace(str1, str2,  mystr.count(str1))
 m6.replace('wang','li') # 'hello li bo and li'
 m6.replace('wang','li',1) # 'hello li bo and wang'
 
 ## split 以 str 为分隔符切片 mystr,如果 maxsplit有指定值,则仅分隔 maxsplit 个子字符串
 ## 函数:split(str=" ", maxsplit)
 m6.split(' ') # ['hello', 'wang', 'bo', 'and', 'wang']
 m6.split('and') # 不留and部分 ['hello wang bo ', ' wang']
 m6.split('wa',1) # 指定切割次数 ['hello ', 'ng bo and wang']
 
 
 ## partition rpartition  以str分割成三部分,str前,str自身和str后
 ## 函数:partition(str)
 m6.partition('and') # ('hello wang bo ', 'and', ' wang')
 m6.rpartition('wang') # ('hello wang bo and ', 'wang', '')
 
 ## splitlines 按照行分隔,返回一个包含各行作为元素的列表,按照换行符分割
 m7='hello\nwang\nbo\nand\nwang'
 m7.splitlines() # ['hello', 'wang', 'bo', 'and', 'wang']
 
 ## startswith 和 endswith 检查字符串是否是以 obj 开头或者结尾, 是则返回 True,否则返回 False
 ## 函数:startswith(obj)   endswith(obj)
 m6.startswith("hello") # True
 m6.endswith("wang") # True
 
 ## lower and upper 转化大小写
 m6.upper() # 'HELLO WANG BO AND WANG'
 
 ## lstrip 删除str 左边的空白字符 当然还要右边 rstrip
 m8=' hello   '
 m8.lstrip() # 'hello   '
 m8.rstrip() # ' hello'
 
 ## isspace  只包含空格,则返回 True,否则返回 False
 m8.isspace() # False
 ' '.isspace() # True 一个空格
 '      '.isspace() # True 多个空格
 
 ## join
 m9=['hello', 'world', 'wangbo', 'and', 'python']
 ' '.join(m9) # 'hello world wangbo and python'
 
 ## count 返回 str在start和end之间 在 mystr里面出现的次数
 ## 函数:count(str, start=0, end=len(str))
 m6.count('wang') # 2
 
 ## capitalize 把字符串的第一个字符大写
 m6.capitalize() # 'Hello wang bo and wang'
 
 ## title 把字符串的每个单词首字母大写
 m6.title() #'Hello Wang Bo And Wang'
 
 ## ljust 返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串
 ## 函数:ljust(width)
## 当然还有rjust 和center
m6.ljust(30) # 'hello wang bo and wang        '
m6.rjust(30) # '        hello wang bo and wang'
m6.center(30) #  '    hello wang bo and wang    '

## isalpha 所有字符都连续的是字母 则返回 True,否则返回 False
m6.isalpha() # False
'hello'.isalpha() # True
'hell8o'.isalpha() # False

## isdigit 只包含数字则返回 True 否则返回 False
'8'.isdigit() # True
'8g'.isdigit() # False

## isalnum 所有字符都是字母或数字则返回 True,否则返回 False
'8g'.isalnum() # True
'8g----'.isalnum() # False

7.列表(list) (结果在注释后面)

n = ['xiaoWang','xiaoZhang','xiaoHua']
 
 ## 取出
 n[1] # 'xiaoZhang'
 
 ## 使用for循环
 for name in n:
     print(name) # xiaoWang xiaoZhang xiaoHua
 
## 使用while循环
index = 0
while index

8.元组(Tuple)

o=(1,[2,3],4,5,6,7,8)

## 修改元组
## Python中不允许修改元组的数据,包括不能删除其中的元素。
##元组是不可变的,也就是说,元组中的元素在被赋值后不能改变。但是,如果元素本身是一个可变数据类型的列表,那么其嵌套项可以被改变
o[1].append(4)
o # (1, [2, 3, 4], 4, 5, 6, 7, 8)

## 元组的内置函数两个count, index
o1=('a','b','c','d','a')
o1.index('a',1,5) # 注意是左闭右开区间   结果:4
o1.count('a') # 2

## tuple函数 uple函数的功能与list函数基本上一样的,以一个序列作为参数并把它转换为元组,如果参数是元组,那么该参数就会被原样返回
o2=[1,2,3,4,5,6,7,8,9]
o3=tuple(o2)
o3 # (1, 2, 3, 4, 5, 6, 7, 8, 9)

## 多维列表/元祖
o4=[(2,3),(4,5)]
o4[0] # (2,3)
o4[0][0] # 2
o5=o4+[(3)]
5 # [(2, 3), (4, 5), 3]

9.字典(dict) 和Map差不多

student= {'name':'who', 'id':100, 'sex':'男', 'address':'中国上海'}
student['name'] # 'who'
student.get("address") # '中国上海'

## 字典的增删改查
    ## 添加元素
student['work']='大数据'
student # {'name': 'who', 'id': 100, 'sex': '男', 'address': '中国上海', 'work': '大数据'}
student[(1,2)]='元组数据'
student # {'name': 'who','id': 100,'sex': '男','address': '中国上海','work': '大数据',(1, 2): '元组数据'}

## 删除元素
# del student['sex']

    ## del删除整个字典
# del student

    ## clear清空整个字典
# student.clear() # {}

    ## pop删除字典指定元素并且得到值
# student.pop('name') # 'who'

    ## popitem删除字典指定元素并且得到值
'''
    随机返回并删除字典中的一对键和值(项)。为什么是随机删除呢?
    因为字典是无序的,没有所谓的“最后一项”或是其它顺序。
    在工作时如果遇到需要逐一删除项的工作,用popitem()方法效率很高
'''
# student.popitem() # ((1, 2), '元组数据')

## 修改元素 通过key修改
student['id'] = 101

## 查找元素
student['id'] # 101


## 字典的键值操作

    ## len() 测量字典中,键值对的个数
len(student) # 6

    ## keys() 返回一个包含字典所有KEY的列表
list(student.keys()) # ['name', 'id', 'sex', 'address', 'work', (1, 2)]

    ## values() 返回一个包含字典所有value的列表
list(student.values()) # ['who', 101, '男', '中国上海', '大数据', '元组数据']

    ## items() 中返回可遍历的(键, 值) 元组数组
list((student.items()))
'''结果:
    [('name', 'who'),
     ('id', 101),
     ('sex', '男'),
     ('address', '中国上海'),
     ('work', '大数据'),
     ((1, 2), '元组数据')]
 '''
## 字典遍历
    ##遍历字典的key(键)
for key in student.keys():
       key

    ## 遍历字典的value(值)
for value in student.values():
    value

     ## 遍历字典的items(元素)
for item in student.items():
    item

    ## 遍历字典的key-value(键值对)
for temp in student.items():
    print('key=%s,value=%s'%(temp[0],temp[1]))
'''结果:
    key=name,value=who
    key=id,value=101
    key=sex,value=男
    key=address,value=中国上海
    key=work,value=大数据
    key=(1, 2),value=元组数据
'''
    ## 使用枚举遍历enumerate()
for i,chr in enumerate(student):
    print('%d:%s' %(i,chr))
'''结果:
0:name
1:id
2:sex
3:address
4:work
5:(1, 2)
'''

10.集合(set)

x=set('abcde')
 x # {'a', 'b', 'c', 'd', 'e'}
 
 y=set(['h','e','l','l','o'])
 y # {'e', 'h', 'l', 'o'}
 
 ## 交集
 x&y # {'e'}
 
## 并集
x|y # {'a', 'b', 'c', 'd', 'e', 'h', 'l', 'o'}

## 差集
y-x # {'h', 'l', 'o'}

## 对称差集(在x和y中,但不会同时出现在二者中)
x^y # {'a', 'b', 'c', 'd', 'h', 'l', 'o'}

11.函数

## 定义函数 标识符由字母、下划线和数字组成,且数字不能开头
'''
def 函数名():
      代码
'''
## 调用函数
'''
函数名()
'''

## 例子(九九乘法表)
    ##定义一个名字叫print_99的函数
def print_99():
    i = 1
    while i <= 9 :
        j = 1
        while j <= i :
            print("%d*%d=%d\t" % (j,i,i*j),end="")
            j += 1
        i += 1
        print("")

        ## 调用函数
# print_99()

## 1.有传参有返回值的函数
    ## 无返回值
def add_num_no_return(a,b):
    print("a+b=%d"%(a+b))

add_num_no_return(100,200) # a+b=300
    ## 有返回值
def add_num_return(a,b):
    return a+b

add_num_return(100,200) # 300

## 2.缺省参数
def print_info1(name, age = 25 ):
    print("name:%s"%name)
    print("age:%d"%age)

    ## 使用 注意:带有默认值的参数一定要位于参数列表的最后面(除非自己指定)
# print_info('wangbo') # name:wangbo age:25
# print_info('wangbo',26) # name:wangbo age:26
# print_info(26,'wangbo') # 报错
# print_info(age=26,name='wangbo') # 指定后可以正常使用

## 3.不定长参数
def print_info2(*names):
    print(names)

# print_info2('zhang','wang','li','zhao') # ('zhang', 'wang', 'li', 'zhao')

## 4.拆包 注意:* 与 ** 的区别

def print_info3(*names,**people):
    print(names)
    print(people)

a=('zhang','wang','li','zhao')
b={'name':'wangbo','age':'25'}
# print_info3(*a,**b) # ('zhang', 'wang', 'li', 'zhao')   {'name': 'wangbo', 'age': '25'}

## 5.引用传参
def add_self(a):
    a+=a
    print(a)

# add_self(a) # ('zhang', 'wang', 'li', 'zhao', 'zhang', 'wang', 'li', 'zhao')

## 6.函数返回多个值
def print_info4():
    a=10
    b=20
    c=30
    return a,b,c
# print_info4() # (10, 20, 30)

12.文件操作

## 使用open函数,可以打开一个已经存在的文件,或者创建一个新文件open(文件名,访问模式)
'''
r: 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。如果文件不存在会崩溃。

w: 打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。

a: 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。
    也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。

rb: 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。

wb:以二进制格式打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。

ab:以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。
    也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。

r+:打开一个文件用于读写。文件指针将会放在文件的开头。

w+:打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。

a+:打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。
    如果该文件不存在,创建新文件用于读写。

rb+:以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。

wb+:以二进制格式打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。

ab+:以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。

'''
## 打开文件open
# w = open('../data/test.txt', 'w')

# w.write('hello world, 欢迎你来到这里')

## 读数据(read)
r = open('../data/test.txt', 'r')

    ## 使用read(num)可以从文件中读取数据,num表示要从文件中读取的数据的长度(单位是字节),如果没有传入num,那么就表示读取文件中所有的数据
# content1 = r.read()
# print(content1)

    ## readlines可以按照行的方式把整个文件中的内容进行一次性读取,并且返回的是一个列表,其中每一行的数据为一个元素
# content2 = r.readlines()
# print(content2)

    ## readline 每次就读一行
# content3 = r.readline()
# print(content3)

## 关闭文件close

r.close()

参数说明列表

参数

解释

r

以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。如果文件不存在会崩溃

w

打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。

a

打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。

rb

以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。

wb

以二进制格式打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。

ab

以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。

r+

打开一个文件用于读写。文件指针将会放在文件的开头。

w+

打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。

a+

打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。

rb+

以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。

wb+

以二进制格式打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。

ab+

以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。

13.简单的文件复制

## 简单的文件复制
old_file=open('../data/test.txt','r')
new_file=open('../data/test_temp.txt','w')
    ## 读取要复制的文件,写到新文件中去
new_file.write(old_file.read())

new_content = open('../data/test_temp.txt','r').readlines()
print(new_content)
old_file.close()
new_file.close()

14.文件读写定位

## 在读写文件的过程中,如果想知道当前的位置,可以使用tell()来获取
# tell = open("../data/test.txt", "r")
# str = tell.read(3)
# print("读取的数据是 : ", str)

    ## 查找当前位置
# position = tell.tell()
# print("当前文件位置 : ", position) 
# tell.close()

## 如果在读写文件的过程中,需要从另外一个位置进行操作的话,可以使用seek()
## seek(offset, from)有2个参数 offset:偏移量 from:方向
      # 0:表示文件开头
      # 1:表示当前位置
      # 2:表示文件末尾
seek = open("../data/test.txt", "r")
seek.seek(3,0) # 从文件开头第三位开始读
str1 = seek.read() 
print("读取的数据是 : ", str1)   # 结果:lo world, 欢迎你来到这里

seek.close()

15.文件的重命名与删除

import os

    ## os模块中的rename()可以完成对文件的重命名操作 
    ## rename(需要修改的文件名, 新的文件名)
# os.rename('../data/test_temp.txt','../data/test_rename.txt')

    ## os模块中的remove()可以完成对文件的删除操作
# os.remove('../data/test_rename.txt')

16.文件夹的相关操作

import os

    ## 1. 创建文件夹
# os.mkdir('../data/test_doc')

    ## 2. 创建多层目录
# os.makedirs('../data/test_doc/a/b/c')

    ## 3. 获取当前目录
os.getcwd() # '/opt/module/jupyter/wangbo/python'

    ## 4. 改变默认目录
# os.chdir("../../") 
# os.getcwd() # '/opt/module/jupyter'

    ## 5. 获取目录列表,包含文件和目录
# os.listdir("./") # ['notebook.log', '.ipynb_checkpoints', 'wangbo']

    ## 6. 删除文件夹
# os.rmdir('/opt/module/jupyter/wangbo/data/test_doc/a/b/c')

    ## 7. 删除多层目录

import shutil
# shutil.rmtree('/opt/module/jupyter/wangbo/data/test_doc')

    ## 恢复到之前的路径下
# os.chdir("/opt/module/jupyter/wangbo/python") 
# os.getcwd()

案例:批量修改文件名

import os
## 先创建一批文件

# os.mkdir("../data/test_doc")
    ## #进入test_doc目录
# os.chdir("../data/test_doc")
# i = 1
# while i <= 10 :
#     open("机器学习-%d.docx" %i,"w")
#     i += 1
# print("创建完毕!")

## 修改:把机器学习-X.docx 修改为 神经网络-X.docx

    ## 1. 得到文件下所有文件的文件名
file_names=os.listdir()

    ## 2. 遍历并修改 
for file_name in file_names:
    print(file_name)
    new_name= "我在学-"+file_name
    os.rename(file_name,new_name)

17.面向对象

## 创建对象
class People(object):

    #初始化函数,用来完成一些默认的设定
    def __init__(self):
        print('我被初始化加载了....')
    def __del__(self):
        print("python解释器开始回收%s" % self)
    def __str__(self):
        return 'welcome people'
    # 方法:吃
    def eat(self):
        print('那个人在吃东西....')

    # 方法:喝
    def drink(self):
        print("那个人在喝水...")

## 创建一个对象,并用变量zhangsan来保存它的引用
zhangsan = People()
## 添加属性
zhangsan.sex='男'
zhangsan.age='88'

## 调用对象方法
zhangsan.eat() # 那个人在吃东西....
zhangsan.drink() # 那个人在喝水...

## 调用属性
print(zhangsan.age)

## 总结
    ## 理解self
# 某个对象调用其方法时,Python解释器会把这个对象作为第一个参数传递给self 通俗的话讲,就是谁调用这个方法就是谁

    ## __init__
# 当创建实例对象成功后,有Python解释器来调用该方法,这个方法不用我们手动调用

    ## id()  方法 即看到的是创建对象在内存中的地址
print(id(zhangsan)) # 例:140142702677008

    ## __str__() 当使用print输出对象的时候,只要自己定义了__str__(self)方法,那么就会打印从在这个方法中return的数据
print(zhangsan) # welcome people

    ## __del__方法 创建多个对象的时候触发__del__方法
# 再创建一个zhangsan2
zhangsan2=People()
zhangsan2.age=23 # python解释器开始回收23

18.面向对象特征:封装

## 封装
## 公有成员变量和私有成员变量  
'''
python中用成员变量的名字来区分是共有成员变量或者是私有成员变量。
python中,以两个下划线‘__’开头的变量都是私有成员变量,而其余的变量都属于公有成员变量。
其中,私有的成员变量只能在类的内部访问,而共有的公有的成员变量可以在类的外部进行访问。
'''
class Person(object):
    def __init__(self, name):
        self.__name = name
    def get_name(self):
        return self.__name

lisi = Person("lisi1")
print(lisi.get_name())
# print(lisi.__name)#会报错


## 公有方法和私有方法
'''
类的方法也分为公有方法和私有方法。
类的私有方法只能通过对象名(在类内部也就是self)在类的内部进行访问。
而公有方法可以在类的外部通过对象名进行访问。
'''

class Test(object):
    #普通方法
    def test(self):
        print("普通方法test")
    #普通方法
    def _test1(self):
        print("普通方法_test1方法")
    #私有方法
    def __test2(self):
        print("私有方法__test2方法")
t = Test()
t.test()
t._test1()
#t.__test2()#调用的时候会报错
'''
python中对象有两种:经典对象和新型对象。
经典对象就是不继承object父类定义出来的对象。
新型对象就是要继承object类定义出的对象。
新型对象和经典对象最大的区别就是,新型对象中提供了对类方法和静态方法的支持。
类方法就是被classmethod()函数处理过的函数,能够直接通过类名进行调用,也能够被对象直接调用。
静态方法相当于类层面的全局函数,可以被类直接调用,可以被所有实例化对象共享,通过staticmethod()定义静态方法,静态方法没有self参数。
'''
class People2(object):
    #类属性
    country = "中国"
    def __init__(self,name):
        self.name = name

    #静态方法
    @staticmethod
    def get_country():
        return People2.country

    @staticmethod
    def print_info(info):
        print(info)

#调用静态方法
print(People2.get_country()) # 中国

19.面向对象特征:继承

# 定义一个父类,如下: 注意点-私有的属性和方法不会被继承
class Cat(object):

    def __init__(self, name, color="白色"):
        self.name = name
        self.color = color

    def run(self):
        print("%s--在跑"%self.name)

    def say(self):
        print("%s--在叫"%self.name)

# 定义一个子类,继承Cat类如下:
class ZhongGuoCat(Cat):

    def set_name(self, newName):
        self.name = newName

    def eat(self):
        print("%s--在吃"%self.name)
        # 重写父类
    def run(self):
        print("%s--在跑"%self.name)
        # super() 调用父类
        super().say()


zhongGuoCat= ZhongGuoCat("中国猫")
print('ZhongGuoCat的名字为:%s'%zhongGuoCat.name)
print('ZhongGuoCat的颜色为:%s'%zhongGuoCat.color)
zhongGuoCat.eat()
zhongGuoCat.set_name('波斯')
zhongGuoCat.run()

'''
ZhongGuoCat的名字为:中国猫
ZhongGuoCat的颜色为:白色
中国猫--在吃
波斯--在跑
波斯--在叫
'''


## 多继承
# 定义一个父类
class A:
    def printA(self):
        print('----A----')
# 定义一个父类
class B:
    def printB(self):
        print('----B----')
# 定义一个子类,继承自A、B
class C(A,B):
    def printC(self):
        print('----C----')

obj_C = C()
obj_C.printA() # ----A---
obj_C.printB() # ----B---
print(C.__mro__) # 搜索搜索过程:(, , , )

20.面向对象特征:多态

## 所谓多态:定义时的类型和运行时的类型不一样,此时就成为多态。

## 多态指的是一类事物有多种形态,(一个抽象类有多个子类,因而多态的概念依赖于继承)
class F1(object):
    def show(self):
        print('F1.show')
class S1(F1):
    def show(self):
        print('S1.show')
class S2(F1):
    def show(self):
        print('S2.show')

        ## Func函数需要接收一个F1类型或者F1子类的类型
def Func(obj):
    obj.show()

s1_obj = S1()
Func(s1_obj) # 在Func函数中传入S1类的对象 s1_obj,执行 S1 的show方法  S1.show
s2_obj = S2()
Func(s2_obj) # 在Func函数中传入Ss类的对象 ss_obj,执行 Ss 的show方法 S2.show

21.异常

'''
异常即是一个事件,该事件会在程序执行过程中发生,影响了程序的正常执行。
一般情况下,在Python无法正常处理程序时就会发生一个异常。
异常是Python对象,表示一个错误。
当Python脚本发生异常时我们需要捕获处理它,否则程序会终止执行。
'''

# error =1/0 # 这样明显的会报错误:ZeroDivisionError
try:
    error =1/0 
except ZeroDivisionError:
    print('发生了异常') # 这样不会报错,程序可以正常执行

    ## 还可以使用else
try:
    success =1/1
except ZeroDivisionError:
    print('发生了异常')
else:
    print("程序没有异常")

    ## try...finally...

try:
    error1 =1/0
except ZeroDivisionError:
    print('发生了异常')
finally:
    print("不管是否错误或者正确都执行finally")

    ## 使用raise抛出系统的异常
# if 4>3:
#     raise Exception('测试一个raise异常')

    ## 自定义异常
class MyException(Exception):
    def __init__(self,message):
        super().__init__()
        self.message=message



class TestExcept(object):
    def start(self):
        try:
            content =input("输入内容:")
            if len(content) < 3:
                raise MyException('测试一个raise异常:长度不够')
        except MyException as s:
            print(s.message)

testExcept = TestExcept()
testExcept.start()

你可能感兴趣的:(Python,python,开发语言)