Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a402b4a

Browse files
committed
Lecture 11
1 parent f8f3ae2 commit a402b4a

File tree

5 files changed

+350
-1
lines changed

5 files changed

+350
-1
lines changed

‎Lecture11.md‎

Lines changed: 267 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,270 @@ KN Pythona wita na kursie Pythona.
1414

1515
Plan:
1616

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+
class Set:
33+
def __init__(self, value = []):
34+
self.data = []
35+
self.concat(value)
36+
37+
def concat(self, value):
38+
for x in value:
39+
if x not in self.data: # Powolne!
40+
self.data.append(x)
41+
```
42+
43+
44+
45+
# Rozszerzanie za pomocą osadzania
46+
47+
48+
```python
49+
...
50+
def union(self, other):
51+
res = self.data[:]
52+
for x in other:
53+
if not x in res:
54+
res.append(x)
55+
return Set(res)
56+
57+
def intersect(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+
return len(self.data)
72+
def __getitem__(self, key):
73+
return self.data[key]
74+
def __and__(self, other):
75+
return self.intersect(other)
76+
def __or__(self, other):
77+
return self.union(other)
78+
def __repr__(self):
79+
return f"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+
class MyList(list):
89+
def __getitem__(self, offset):
90+
print(f"Indeksowanie {self} na pozycji {offset}")
91+
return list.__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.
110+
111+
112+
# Klasa typu
113+
114+
```python
115+
class A:
116+
pass
117+
118+
x = A()
119+
print(type(x)) # <class '__main__.A'>
120+
```
121+
122+
123+
# Klasa typu
124+
125+
```python
126+
A = type("A", (), {})
127+
x = A()
128+
print(type(x)) # <class '__main__.A'>
129+
```
130+
131+
132+
# Klasa typu
133+
134+
```python
135+
def outside_init(self, name):
136+
self.name = name
137+
Robot = type('Robot', (), {"__init__": outside_init,
138+
"say_hello": lambda self: f"Hello {self.name}"})
139+
140+
```
141+
142+
143+
# Dziedziczenie diamentowe
144+
145+
W dziedziczeniu diamentowym wyszukiwanie w drzewie klas zachodzi najpierw wszerz, od lewej do prawej.
146+
147+
148+
# Sloty
149+
150+
```python
151+
class limiter:
152+
__slots__ = ['age', 'name', 'job']
153+
154+
x = limiter()
155+
x.age # Attribute error: age
156+
x.age = 42
157+
x.age # 42
158+
x.ape = 1000 # Attribute error
159+
```
160+
161+
162+
# Sloty
163+
164+
```python
165+
class D:
166+
__slots__ = ['a', 'b', '__dict__']
167+
168+
d = D()
169+
d.a, d.b, d.c = 1, 2, 3
170+
```
171+
172+
# Właściwości klas
173+
174+
```python
175+
class newprops:
176+
def getage(self):
177+
return 40
178+
def setage(self, value):
179+
print("Ustawianie wieku " + str(value))
180+
self._age = value
181+
age = property(getage, setage, None, None)
182+
```
183+
184+
185+
# Metody statyczne i metody klas
186+
187+
```python
188+
class Methods:
189+
def imeth(self, x):
190+
print(self, x)
191+
def smeth(x):
192+
print(x)
193+
def cmeth(cls, x):
194+
print(cls, x)
195+
smeth = stathicmethod(smeth) # ew. wstawienie funkcji
196+
cmeth = classmethod(cmeth)
197+
```
198+
199+
200+
# Metody statyczne
201+
202+
```python
203+
class A:
204+
count = 0
205+
def __init__(self):
206+
A.count += 1
207+
def print_count():
208+
print(A.count)
209+
print_count = stathicmethod(print_count)
210+
```
211+
212+
213+
# Metody klas
214+
215+
```python
216+
class B:
217+
count = 0
218+
def __init__(self):
219+
B.count += 1
220+
def print_count(cls):
221+
print(cls.count)
222+
print_count = classmethod(print_count)
223+
```
224+
225+
226+
# Metody klas
227+
228+
```python
229+
class C:
230+
count = 0
231+
def count(cls):
232+
cls.count += 1
233+
def __init__(self):
234+
self.count()
235+
count = classmethod(count)
236+
```
237+
238+
239+
# Dekoratory - wstęp
240+
241+
```python
242+
class E:
243+
def meth():
244+
pass
245+
meth = staticmethod(meth)
246+
```
247+
248+
249+
# Dekoratory - wstęp
250+
251+
```python
252+
class E:
253+
@staticmethod
254+
def meth():
255+
pass
256+
```
257+
258+
259+
# Dekoratory
260+
261+
```python
262+
class tracer:
263+
def __init__(self, func):
264+
self.calls = 0
265+
self.func = func
266+
def __call__(self, *args, **kwargs):
267+
self.calls += 1
268+
print(f"{self.calls} call of func")
269+
return self.func(*args, **kwargs)
270+
```
271+
272+
273+
# Dekoratory
274+
275+
```python
276+
@tracer
277+
def spam(a):
278+
print(a)
279+
280+
spam(1)
281+
spam(2)
282+
spam(3)
283+
```

‎Lecture11.pdf‎

167 KB
Binary file not shown.

‎Lecture11/integers.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class good_int(int):
2+
def __new__(cls, value):
3+
if value in {2137, 69}:
4+
print('Nice!')
5+
return int.__new__(cls, value)
6+
7+
gi = good_int(12)
8+
9+
print(gi)
10+
11+
gi2 = good_int(69)
12+
gi3 = good_int(2137)
13+
14+
15+
print(gi2 + gi3)
16+
17+
18+

‎Lecture11/mylist.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
class MyList(list):
2+
def __getitem__(self, offset):
3+
print(f"Indeksowanie {self} na pozycji {offset}")
4+
return list.__getitem__(self, offset - 1)
5+
ml = MyList()
6+
ml.append(12)
7+
ml.append(13)
8+
print(ml[1])

‎Lecture11/set.py‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# coding=utf-8
2+
"""
3+
Module reimplements set class for educational purposes.
4+
"""
5+
6+
class Set:
7+
def __init__(self, value = []):
8+
self.data = []
9+
self.concat(value)
10+
11+
def concat(self, value):
12+
for x in value:
13+
if x not in self.data: # Powolne!
14+
self.data.append(x)
15+
16+
def union(self, other):
17+
res = self.data[:]
18+
for x in other:
19+
if not x in res:
20+
res.append(x)
21+
return Set(res)
22+
23+
def intersect(self, other):
24+
res = []
25+
for x in other:
26+
if x in other:
27+
res.append(x)
28+
return Set(res)
29+
30+
def __len__(self):
31+
return len(self.data)
32+
33+
def __getitem__(self, key):
34+
return self.data[key]
35+
36+
def __and__(self, other):
37+
return self.intersect(other)
38+
39+
def __or__(self, other):
40+
return self.union(other)
41+
42+
def __repr__(self):
43+
return f"Set: {repr(self.data)}"
44+
45+
46+
if __name__ == '__main__':
47+
a = Set([12, 12, 13])
48+
print(a)
49+
50+
b = Set([12, 14])
51+
print(b)
52+
53+
print(a & b)
54+
55+
print(a | b)
56+
57+
print(len(a | b))

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /