您的位置:首页 > 编程语言 > Python开发

Python入门8_方法,属性,迭代器

2017-08-19 10:11 399 查看
1,继承机制:

上章讲到了class man(human): 这个表示类man继承human。下面介绍super( ),一个例子如下:

>>> class human:
def __init__(self):
self.gender = 'man'
def say(self):
if self.gender == 'man':
print 'I am a man'
else:
print 'I am a women'
>>> class man(human):
def __init__(self):
self.name = 'Jack Ma'

>>> f = man()
>>> f.name
'Jack Ma'
>>> f.gender
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: man instance has no attribute 'gender'
>>> f.say()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: man instance has no attribute 'gender'


做了如下修改:

>>> class man(human):
def __init__(self):
super(man,self).__init__()
self.name = 'Jack Ma'
>>> f = man()
>>> f.say()
TypeError: super() argument 1 must be type, not classobj
# 这个python2会报错,python3没有问题


2,静态方法(可以直接通过类名调用的方法):

>>> class myclass{
@staticmethod
def mmm():
print "mmm"
@classmethod
def nnn():
print "nnn"
}
>>> myclass.mmm()#直接通过类名调用


3,迭代器:

#迭代器使用自己的方法:
>>> class fibolacci:
def __init__(self):
self.a = 0
self.b = 1
def next(self):
self.a,self.b = self.b,self.a+self.b
def __iter__(self):
return self
>>> fib = fibolacci()
>>> for f in fib:
if(f>1000):
print f
break
1597
#for循环内部事实上就是先调用iter()把Iterable变成Iterator在进行循环迭代的
>>> x = [1,3,4]
>>> i = iter(x)
>>> next(i)
1
>>> next(i)
3
>>> next(i)
4
#如果上面那个不好理解,那下面这个在网上找的可能更好理解:
class Fabs(object):
def __init__(self,max):
self.max = max
self.n, self.a, self.b = 0, 0, 1  #特别指出:第0项是0,第1项是第一个1.整个数列从1开始
def __iter__(self):
return self
def next(self):
if self.n < self.max:
r = self.b
self.a, self.b = self.b, self.a + self.b
self.n = self.n + 1
return r
raise StopIteration()

print Fabs(5)
for key in Fabs(5):
print key
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 迭代器 继承