python类、方法、继承、模组、异常、抛出异常raise实例讲解

时间:2018-11-07
本文章向大家介绍python类、方法、继承、模组、异常、抛出异常raise实例讲解,需要的朋友可以参考一下

类和方法

创建类

class A(object):

    def add(self, a,b ):
        return a+b

count = A()
print(count.add(3,5))

初始化工作

class A():
    def __init__(self,a,b):
        self.a = int(a)

        self.b =int(b)

    def add(self):
        return self.a+self.b

count = A('4',5)
print(count.add())

9

继承

class A():
    def add(self, a, b):
        return a+b

class B(A):

    def sub(self, a,b):
        return a-b

print(B().add(4,5))

9

模组

也叫类库和模块。

引用模块

import...或from ... import...来引用模块

引用时间

import time
print (time.ctime())

Wed Nov 7 16:18:07 2018

只引用ctime()方法

from time import ctime

print(ctime())

Wed Nov 7 16:19:53 2018

全部引用

from time import *

from time import *

print(ctime())
print("休眠两秒")
sleep(2)
print(ctime())

Wed Nov 7 16:26:37 2018
休眠两秒
Wed Nov 7 16:26:39 2018

模块调用

目录样式

project/
   pub.py
   count.py

pub.py

def add(a,b)
    return a +b

count.py

from pub import add
print(add(4,5))

9

跨目录调用

目录样式

project
   model
       pub.py
   count.py
from model.pub import add
print add(4,5)

--
这里面有多级目录的还是不太了解,再看一下

异常

文件异常

open('abc.txt','r') #报异常

python3.0以上

try:
    open('abc.txt','r')
except FileNotFoundError:
    print("异常")

python2.7不能识别FileNotFoundError,得用IOError

try:
    open('abc.txt','r')
except IOError:
    print("异常")

名称异常

try:
    print(abc)
except NameError:
    print("异常")

使用父级接收异常处理

所有的异常都继承于Exception

try:
    open('abc.txt','r')
except Exception:
    print("异常")

继承自BaseException

Exception继承于BaseException。
也可以使用BaseException来接收所有的异常。

try:
    open('abc.txt','r')
except BaseException:
    print("异常")

打印异常消息

try:
    open('abc.txt','r')
    print(aa)
except BaseException as msg:
    print(msg)

[Errno 2] No such file or directory: 'abc.txt'

更多异常方法

try:
    aa = "异常测试"
    print(aa)
except Exception as msg:
    print (msg)
else:
    print ("good")

异常测试
good

还可以使用 try... except...finally...

try:
    print(aa)
except Exception as e:
    print (e)
finally:
    print("always do")

name 'aa' is not defined
always do

抛出异常raise

from random import randint

#生成随机数

number = randint(1,9)

if number % 2 == 0:
    raise NameError ("%d is even" %number)
else:
    raise NameError ("%d is odd" %number)

Traceback (most recent call last):
File "C:/Python27/raise.py", line 8, in