1. 程式人生 > >python入門(續)

python入門(續)

except all 打印 化工 print trac pen txt not

類和方法

創建類

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

python入門(續)