python类知识

来源:互联网 发布:js 定义json对象 编辑:程序博客网 时间:2024/04/30 02:21

标准库random中包含choice函数,可以从序列中随机选出元素,如:

>>> from random import choice>>> x = choice(['hello, world!', [1,2,'e','e', 4]])>>> x'hello, world!'

以上x可能是这个值,也可能是后面的列表。


python类:类中的函数名前加双下划线就可以使函数成为私有的,外部不能访问。类的成员变量直接在类中初始化,在变量名前加单下划线,则变成私有变量,不能被带星号的import语句导入(from module import *导入), 类的方法与其他函数的区别是方法总是将对象作为自己的第一个参数,即self参数

python继承:父类写在类名的括号里,如下:

#coding=utf-8#python继承,父类在类后的括号中定义class Filter:    def init(self):        self.blocked = []    def filter(self, sequence):  #过滤在blocked中的内容        return [x for x in sequence if x not in self.blocked]#作用:过滤SPAMclass SPAMFilter(Filter):    def init(self):  #重写init        self.blocked = ['SPAM']def main():    f = Filter()    f.init()    lf = f.filter([1,2,3])    print lf    sf = SPAMFilter()    sf.init()    print sf.blocked    print sf.filter(['SPAM', 'SPAM', 'SPAM', 'hello', 'world'])if __name__ == '__main__':    main()
issubclass(child, parent):判断一个类是否是另一个类的子类

如果想要知道自己的基类(们):使用__bases__特性(复数),SPAMFilter.__bases__

isinstance:查看一个对象是否是一个类的实例,也可以用于基本类型,如str,

如果想知道对象属于哪个类,使用__class__特性: s.__class__,如果是新式类,使用type(s)也可以得出是属于什么类


多个超类:

#coding=utf-8#python的多继承class Calculator:    def calculator(self, expression):        self.value = eval(expression)class Talker:    def talk(self):        print 'Hi, my value is', self.value#子类,继承以上两个类class TalkingCalculator(Calculator, Talker):    passdef main():    tc = TalkingCalculator()    tc.calculator('1+2*3')    tc.talk()if __name__ == '__main__':    main()
多重继承需要注意:如果一个方法从多个超类继承,必须注意超类的顺序,先继承的类中的方法会重写后继承的类的方法。

callable(object):确定对象是否可调用,比如函数或方法,python3已经废弃,可以使用hasattr(x, '__call__')代替,如callable(getattr(tc, 'talk', None))

getattr(object, name[,default]):确定特性的值,可提供默认值,以便特性在不存在时使用。

setattr(object, name, value):设定对象的给定特性为value

hasattr(object, name):确定对象是否有指定特性。


python异常处理,raise可以引发异常,它接受异常类或异常实例作为参数,自定义异常类:继承Exception类的方法创建自定义异常类,如果异常在函数内不被处理,就会传播至函数调用的地方。如果那里也没有处理,会继续传播,一直到达主程序,如果那里没有异常处理,程序会带着堆栈跟踪中止。

设置异常屏蔽位:

#屏蔽异常,即选择是把异常吞掉还是传播class MuffledCalculator:    muffled = False  #控制异常处理方式    def calc(self, expr):        try:            return eval(expr)        except ZeroDivisionError:            if self.muffled:                print 'Division by zero is illegal'            else:                raise  #如果没有打开屏蔽异常,则传播出去def testMyffled():    calculator = MuffledCalculator()    calculator.muffled = True #打开屏蔽异常位    calculator.calc('10/0')   #打印错误    calculator.muffled = False  #不屏蔽异常    calculator.calc('10/2')    calculator.calc('10/0')   #异常抛出,程序终止if __name__ == '__main__':    testMyffled()

结果:

xlf@xlf-Lenovo:~/python$ python except.pyDivision by zero is illegalTraceback (most recent call last):  File "except.py", line 25, in <module>    testMyffled()  File "except.py", line 22, in testMyffled    calculator.calc('10/0')   #异常抛出,程序终止  File "except.py", line 9, in calc    return eval(expr)  File "<string>", line 1, in <module>ZeroDivisionError: integer division or modulo by zero

捕捉多个异常, except后接多个异常类,如果不接任何值,表示捕捉所有异常

else:如果try块没有发生异常,else被执行

finally:不管是否发生异常都会执行!

#异常处理def excepts():    while True:  #如果输入错误则一直输入直到没有错误发生        try:            x = input("Enter the first number: ")            y = input("Enter the second number: ")            print x/y        except (ZeroDivisionError, TypeError, NameError) as e:            print "something wrong:", e   #捕捉多个异常,并且打印异常信息            print 'Invalid input, please try again'        except Exception as e: #捕捉剩下的所有异常            print "wrong: ", e            print 'Invalid input, please try again'        else:   #当没有异常发生时退出循环            break        finally:  #不管异常是否会发生总会执行,这里就算正确运行,break循环,还是会执行哟哟!!            print "aha, I'm finally, you must exec me"

finally:通常在异常后进行清理,通常可以关闭文件或网络套接字。


python:魔法方法

构造方法: __init__,对于子类的构造方法,需要调用父类的构造方法,有以下两种调用方式:

#python构造方法class Bird:    def __init__(self): #构造方法        self.hungry = True    def eat(selft):        if self.hungry:            print 'Aaaah...'            self.hungry = False        else:            print 'No, thanks'class SongBird(Bird):    def __init__(self):  #如果重写了构造方法,需要调用父类的构造方法        #方法1:未绑定方法,通过类名调用,将self传递过去        Bird.__init__(self)    #先初始化父类        #方法2:super函数,参数类和对象做参数,再调用父类init函数        super(SongBird, self).__init__()        self.sound = 'Squawk'  #初始化自己的成员    def sing(self):        print self.sound
一个概念,绑定方法与未绑定方法的区别

绑定方法:通过类的实例调用方法,self会自动绑定到该实例

未绑定方法:通过类直接调用方法,即没有实例被被绑定到self,可以自由传递需要的self参数


子类化列表,字典和字符串,标准库有3个关于序列和映射规则(UserList,UserString和UserDict)可以立即使用的实现,新版本中可以直接子类化内建类型,如list等,如下一个例子,以下类继承了list的所有方法,只是加了个counterlist:

#python子类化内建类型#继承内建类型list,只是加了一个counter,访问一次加一class CounterList(list):    def __init__(self, *args):        super(CounterList, self).__init__(*args)        self.counter = 0    def __getitem__(self, index):        self.counter += 1        return super(CounterList, self).__getitem__(index)
运行例子:

>>> c1 = CounterList(range(10))>>> c1[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> c1.reverse()>>> c1[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]>>> del c1[3:6]>>> c1[9, 8, 7, 3, 2, 1, 0]>>> c1.counter0>>> c1[4]+c1[2]9>>> c1.counter

python中通过property函数可以一个从现有属性中创建一个新的属性,property有四个参数:fget, fset, fdel, doc--,第三四个是可选的,只选用第一个表示产生的属性是只读的,令可以使用关键字参数来定义属性,property实际上不是真正的函数,它是拥有很多特殊方法的类。如下示例:

#python:property函数创建属性__metaclass__=typeclass Rectangle:         #类中记得self方法,函数第一个参数是self,调用属性用self.xxx    def __init__(self):  #构造方法中直接定义属性        self.width = 0        self.height = 0    def setSize(self, size):        self.width, self.height = size    def getSize(self):        return self.width, self.height    #创建一个属性,getSize, setSize做参数,客户端可直接取用size,不用再调用getSize,setSize    size = property(getSize, setSize)     
以下为使用方法:

>>> r = Rectangle()>>> r.width=10>>> r.height=5>>> r.size(10, 5)>>> r.size=150,100>>> r.size(150, 100)

静态方法与类成员方法,

静态方法与类成员方法在创建时分别被装入Staticmethod和Classmethod类型的对象中。静态方法没有self参数,且能够被类自身直接调用。类方法在定义时需要名为cls的类似self的参数,类成员方法可以直接用类的具体对象调用,但cls参数是自动被绑定到类的,可以使用装饰器语法,使用@操作符,在函数的商法将装饰器列出,从而可以指定一个或多个装饰器。如下类:

#python:静态方法与类成员方法class MyClass:    @staticmethod   #装饰器,下面的函数都是静态方法    def smethod():        print 'This is a static method'        @classmethod    def cmethod(cls):        print 'This is a class method of', cls
运行:

>>> MyClass.smethod()This is a static method>>> MyClass.cmethod()This is a class method of method.MyClass





0 0