XD blog

blog page

iterator


2016-02-28 Python 2.7 and Python 3, difference with multiple inheritance

There is a little difference in the way Python 3 and Python 2.7 handles multiple inheritance. Class Cl inherits from ClA and ClB. ClA defines method1, ClB defines suffix. The question is: Does method method1 from class ClA know about method suffix from class ClB? In Python 3, it does:

class C0:
    def suffix(self):
        raise NotImplementedError()

class ClA(C0):
    def method1(self):
        return "A.method1" + self.suffix()
        
class ClB(C0):
    def suffix(self):
        return "--B"
        
class Cl(ClA, ClB):
    pass

cl = Cl()
print(cl.method1())

[1]

A.method1--B

In Python 2.7?


more...

2016-02-26 Don't mix return and yield

When a function uses the keyword yield, it becomes a generator. A second function can accept this generator and produce another one as follows.

def generator(seq):
    for v in range(0,3):
        yield v+1
        
def generator2(gen):
    for r in gen:
        yield r

for v in generator2(generator(3)):
    print(v)

[1]

1
2
3

This is not the only way to write this function. Python 3.5 has introduction keyword yield from.


more...

Xavier Dupré