欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python入门(续)

程序员文章站 2023-01-24 17:32:19
类和方法 创建类 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) s ......

类和方法

创建类

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