Skip to content

Commit 3d1a663

Browse files
Merge pull request #31 from pro1code1hack/10_Mixin
10 mixin
2 parents fb45fe4 + 7a5c220 commit 3d1a663

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# Mixin
2+
3+
_A class that offers method implementations for reuse by several connected child classes is
4+
known as a mixin. The inheritance does not, however, establish a connection._
5+
6+
_A mixin collects a group of techniques for reuse. Each mixin should implement a single
7+
distinct behavior using techniques that are closely related._
8+
9+
_Mixin classes should be named with the suffix Mixin because Python does not specify a formal way to define them._
10+
11+
+ Example:
12+
13+
```python
14+
class Graphic:
15+
def __init__(self, pos_x, pos_y, size_x, size_y):
16+
self.pos_x = pos_x
17+
self.pos_y = pos_y
18+
self.size_x = size_x
19+
self.size_y = size_y
20+
21+
22+
class Mixin:
23+
def resize(self, size_x, size_y):
24+
self.size_x = size_x
25+
self.size_y = size_y
26+
27+
28+
class ResizableClass(Mixin, Graphic):
29+
pass
30+
31+
32+
rge = ResizableGraphicalEntity(6, 2, 20, 30)
33+
rge.resize(200, 300)
34+
```
35+
36+
_Here, the class Mixin derives straight from object rather than Graphic,
37+
therefore ResizableClass just receives the resize function from it._
38+
39+
_As we previously stated, this makes the ResizableClass
40+
inheritance tree simpler and lowers the danger of the diamond problem._
41+
42+
_It frees us from having to inherit undesirable methods when using Graphic
43+
as a parent for other types._
44+
45+
_Tips:_
46+
47+
+ Simple class modifications are added using mixin classes.
48+
+ Python uses multiple inheritance to implement mixins, which have a powerful expressive capacity but call for careful
49+
design.

0 commit comments

Comments
 (0)