You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: Lecture11.md
+267-1Lines changed: 267 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -14,4 +14,270 @@ KN Pythona wita na kursie Pythona.
14
14
15
15
Plan:
16
16
17
-
+ Zaawansowane zagadnienia związane z klasami
17
+
+ Zaawansowane zagadnienia związane z klasami
18
+
19
+
20
+
# Rozszerzanie typów wbudowanych
21
+
22
+
Technika:
23
+
24
+
- Rozszerzanie za pomocą osadzania
25
+
- Rozszerzanie za pomocą klas podrzędnych
26
+
27
+
28
+
29
+
# Rozszerzanie typów za pomocą osadzania
30
+
31
+
```python
32
+
classSet:
33
+
def__init__(self, value= []):
34
+
self.data = []
35
+
self.concat(value)
36
+
37
+
defconcat(self, value):
38
+
for x in value:
39
+
if x notinself.data: # Powolne!
40
+
self.data.append(x)
41
+
```
42
+
43
+
44
+
45
+
# Rozszerzanie za pomocą osadzania
46
+
47
+
48
+
```python
49
+
...
50
+
defunion(self, other):
51
+
res =self.data[:]
52
+
for x in other:
53
+
ifnot x in res:
54
+
res.append(x)
55
+
return Set(res)
56
+
57
+
defintersect(self, other):
58
+
res = []
59
+
for x in other:
60
+
if x in other:
61
+
res.append(x)
62
+
return Set(res)
63
+
```
64
+
65
+
66
+
67
+
# Rozszerzanie za pomocą osadzania
68
+
69
+
```python
70
+
def__len__(self):
71
+
returnlen(self.data)
72
+
def__getitem__(self, key):
73
+
returnself.data[key]
74
+
def__and__(self, other):
75
+
returnself.intersect(other)
76
+
def__or__(self, other):
77
+
returnself.union(other)
78
+
def__repr__(self):
79
+
returnf"Set: {repr(self.data)}"
80
+
```
81
+
82
+
83
+
84
+
# Rozszerzanie za pomocą klas podrzędnych
85
+
86
+
```python
87
+
# Lista indeksowana od 1..N
88
+
classMyList(list):
89
+
def__getitem__(self, offset):
90
+
print(f"Indeksowanie {self} na pozycji {offset}")
91
+
returnlist.__getitem__(self, offset -1)
92
+
```
93
+
94
+
95
+
# Klasy w nowym stylu
96
+
97
+
Od Pythona 3.0 wszystkie klasy są automatycznie tworzone jako klasy w nowym stylu - dziedziczą po klasie __object__ niezależnie od podania jawnej deklaracji class A(object).
98
+
99
+
100
+
101
+
# Połączenie klas i typów
102
+
103
+
Klasy są typami, a typy są klasami. Funkcja wbudowana type(I) zwróci klasę, z której utworzono obiekt I, nie generyczny typ i najczęściej jest to ta sama klasa, którą zawiera I._ _ class _ _.
104
+
105
+
106
+
107
+
# Połączenie klas i typów
108
+
109
+
Co więcej, klasy są instancjami klasy type; Można również tworzyć klasy potomne klasy type, co pozwala na dostosowanie do własnych potrzeb mechanizmu tworzenia klas. Wszystkie klasy dziedziczą po klasie object i to samo dotyczy klasy type.
0 commit comments