Extension boom

Imaine

there is a fruit shop and it sells apple, banana,pineapple,watermelon.then we can define like:

1
2
3
4
5
6
7
8
9
10
class Fruit():
pass
class Apple(Fruit):
pass
class Banana(Fruit):
pass
class Pineapple(Fruit):
pass
class Watermelon(Fruit):
pass

That’s so easy!

One day

The owner need to distinguish local and foreign fruit. No problem, let’s extending them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Fruit():
pass
class LocalityFruit(Fruit):
def locality(self):
return True
class NonLocalityFruit(Fruit):
def locality(self):
return False
class Apple(LocalityFruit):
pass
class Apple(NonLocalityFruit):
pass
class Banana(LocalityFruit):
pass
class Banana(NonLocalityFruit):
pass

Another day

Owner need to distinguish pare or not fruit. WTH, kill me now please.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Fruit():
pass
class LocalityFruit(Fruit):
def locality(self):
return True
class NonLocalityFruit(Fruit):
def locality(self):
return False


class PareLocalFruit(LocalityFruit):
def need_pare(self):
return True
class PareNonLocalFruit(NonLocalityFruit):
def need_pare(self):
return True

class NonPareLocalFruit(LocalityFruit):
def need_pare(self):
return False

class NonPareNonLocalFruit(NonLocalityFruit):
def need_pare(self):
return False

class Apple1(PareLocalFruit):pass
class Apple2(PareNonLocalFruit):pass
class Apple3(NonPareLocalFruit):pass
class Apple4(NonPareNonLocalFruit):pass

class Banana1(PareLocalFruit):pass
class Banana2(PareNonLocalFruit):pass
class Banana3(NonPareLocalFruit):pass
class Banana4(NonPareNonLocalFruit):pass

Another day again

Owner need ……. Owner is dead because we kill him/her

Class will be exploded.

Howto

In Python, we could use Mixin and we can write those class like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Fruit():
pass
class LocalityMixin():
def locality(self):
return True
class NonLocalityMixin():
def locality(self):
return False
class PareMixin():
def need_pare(self):
return True
class NonPareMixin():
def need_pare(self):
return False

class Apple1(Fruit, LocalityMixin, PareMixin):pass
class Apple2(Fruit, NonLocalityMixin, PareMixin):pass
class Apple3(Fruit, LocalityMixin, NonPareMixin):pass
class Apple3(Fruit, NonLocalityMixin, NonPareMixin):pass

If you know Java, it just like implements

1
2
3
...
class A extends B implements C,D,E,F
...

Python make it simple and easy.

I love this world.

EOF.