python入门(续)

Python类与异常处理
本文详细介绍了Python中类的创建、初始化、继承以及模块的引用方法。通过实例演示了类的使用,包括如何定义类、创建对象、调用方法。同时,深入探讨了异常处理,包括常见异常类型、如何捕获和处理异常,以及如何自定义异常。

类和方法

创建类

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
raise NameError ("%d is even" %number)
NameError: 4 is even

转载于:https://www.cnblogs.com/newctm/p/9923823.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值