Chinaunix首页 | 论坛 | 博客
  • 博客访问: 19730562
  • 博文数量: 679
  • 博客积分: 10495
  • 博客等级: 上将
  • 技术积分: 9308
  • 用 户 组: 普通用户
  • 注册时间: 2006-07-18 10:51
文章分类

全部博文(679)

文章存档

2012年(5)

2011年(38)

2010年(86)

2009年(145)

2008年(170)

2007年(165)

2006年(89)

分类: 项目管理

2009-08-31 17:37:40

特殊方法、属性、迭代器

构造函数

class FooBar:

    def __init__(self):

        self.somevar = 42

析构函数: __del__

 

继承父类的构造函数

class SongBird(Bird):

    def __init__(self):

        Bird.__init__(self)

        self.sound = 'Squawk!'

    def sing(self):

        print self.sound

另外一种方法:

__metaclass__ = type # super only works with new-style classes

class Bird:

    def __init__(self):

        self.hungry = True

    def eat(self):

        if self.hungry:

            print 'Aaaah...'

            self.hungry = False

        else:

            print 'No, thanks!'

class SongBird(Bird):

    def __init__(self):

        super(SongBird, self).__init__()

        self.sound = 'Squawk!'

    def sing(self):

        print self.sound

 

项目访问

__len__(self):

__nonzero__

__getitem__(self, key):

__setitem__(self, key, value):

__delitem__(self, key):

       这块有待以后深入了解

 

 

属性

__metaclass__ = type

class Rectangle:

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

size = property(getSize, setSize)

 

 

静态方法和类方法:

class MyClass:

@staticmethod

def smeth():

print 'This is a static method'

@classmethod

def cmeth(cls):

print 'This is a class method of', cls

 

 

__getattribute__

__getattr__(self, name):

__setattr__(self, name, value):

__delattr__(self, name):

 

迭代器:

class Fibs:

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 self

 

 

>>> nested = [[1, 2], [3, 4], [5]]

>>> for num in flatten(nested):

print num

...

1

2

3

4

5

or

>>> list(flatten(nested))

[1, 2, 3, 4, 5]

 

本节余下部分待以后总结。

阅读(3089) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~