python 中的内置函数 与 类

来源:互联网 发布:m1a2sep各项数据 编辑:程序博客网 时间:2024/05/22 06:14

python这种语言的变量命名规则有些奇葩,我相信大家已经遇到过了,比如:__future__。这种特殊的形式表明,这个

变量有特殊的意义,你不可以在自己的代码中创造这类变量。

1.__init__() 构造函数

类似于c++,java等面向对象语言,python 在类的定义中也有构造函数,这就是__init__()

__init__(parameters)中的变量parameter用来构建这个类的变量

例如:

class newclass(object):"""docsng for newclass"""    def __init__(self, aStr):        self.aStr = aStrprint "constructor is been used. "+self.aStr+" has been created"hahaha = newclass("hello")

结果就是,constructor is been used. hello has been created

2.__del__() 析构函数

python 不需要进行内存管理,当一个类被扔到垃圾箱(garbage-collected)的时候,这个函数就会发挥功效。但是,你不会知道具体它什么时候起作用,还是远离它比较好。

3说说__init__()被重载(override)的情况

class Bird(object):    def __init__(self):        self.hungry = True    def eat(self):if self.hungry:    print "Great"    self.hungry = Falseelse:    print "No,thanks"


如果运行如下程序:

aBird = singBird()aBird.eat()
程序会报错,因为没有了self.hungry这个变量

解决办法为:

class singBird(Bird):    def __init__(self):Bird.__init__(self)print "i am singing"



class singBird(Bird):    def __init__(self):super(singBird,self).__init__()print "i am singing"


4.简述python类中常用的内置函数

假设我们有一个字典 aDict = {'a': 1,‘b’:2}

__len__(self) 返回序列中收集item的个数 ,对于空的字典,列表,字符串,元组,它们的逻辑值为False 

                      相当于len(aDict)

__getitem__(self,key) 返回与key相对应的值 。相当于aDict[key]

__setitem__(self.key,value) 将与key相对应的值设为value 。相当于aDict[key] = value

__delitem__(self,key) 将key与和key对应的item删掉      del(aDict[key])

对于序列(元组,列表,字符串)aList[-n] 相当于 aList[len(aList)-n]

5.静态方法(staticmethod)和类方法(classmethod)

class myclass(object):    def smeth():        print "this is a static method"    def cmeth(cls):        print "this is a class method",cls    cmeth = classmethod(cmeth)

这就是传说中的装饰器 

class myclass(object):    @staticmethod    def smeth():        print "this is a static method"    @classmethod    def cmeth(cls):        print "this is a class method",cls
当你使用@字符时,装饰器(deractor)的使用就更加简便。

调用myclass.smeth() 输出 this is a static method

调用myclass.cmeth() 输出 this is a class method <class '__main__.myclass'>

6.attribute 函数

__getattribute__(slef,name) 当使用名字为name的attribute时自动调用

__getattr__(self,name) 当使用名字为name的attribute时,实际上并不存在名字为name的attribute时,自动调用

__setattr__(self,name,value)赋值自动调用

__delattr__(self,name) 删除自动调用

例如:

class Rectangle(object):    def __init__(self):        self.width = 0        self.heigh = 0    def __setattr__(self,name,value):        if name  == 'width':            self.width =value        elif name == 'heigh':            self.heigh = value        else:            raise AttributeError    def __getattar__(self,name):        if name == 'width':            return self.width        elif name == 'heigh':            return self.heigh        else:            raise AttributeError

7. 迭代器Iterator

迭代器的功能非常强大,可以对任何对象进行循环

迭代的方式可以利用next()函数,或是for 循环

利用next()函数要注意:最后一个对象后,再进行next(),会产生StopIteration报错

注意:在python 3.0中,next() 函数变为__next__()

class Fibb(object):    def __init__(self):        self.a = 0        self.b = 1    def next(self):        self.a,self.b = self.b, self.a + self.b        return self.a    def __iter__(self):        return selffib = Fibb()print next(fib)print fib.next()for i in fib:    if i >800:        print i         break

总而言之,含有__iter__()的类都是可迭代的,

含有next()的类才是迭代器。

所以对可迭代的类可以使用iter()函数

例如:

a =iter("anasiaj")print a.next()print a.next()
于是,有的人就会问,自己创造的迭代器,可不可以自己设定结束点呢?

当然可以,StopIteration 就相当于循环中的break

例子如下:

class aIter(object):    def __init__(self):        self.value = 0    def next(self):        self.value += 1        if self.value > 15:            raise StopIteration        return self.value    def __iter__(self):        return selfaList = list(aIter())print aList









0 0
原创粉丝点击