1 | n/a | # This contains most of the executable examples from Guido's descr |
---|
2 | n/a | # tutorial, once at |
---|
3 | n/a | # |
---|
4 | n/a | # http://www.python.org/2.2/descrintro.html |
---|
5 | n/a | # |
---|
6 | n/a | # A few examples left implicit in the writeup were fleshed out, a few were |
---|
7 | n/a | # skipped due to lack of interest (e.g., faking super() by hand isn't |
---|
8 | n/a | # of much interest anymore), and a few were fiddled to make the output |
---|
9 | n/a | # deterministic. |
---|
10 | n/a | |
---|
11 | n/a | from test.support import sortdict |
---|
12 | n/a | import pprint |
---|
13 | n/a | |
---|
14 | n/a | class defaultdict(dict): |
---|
15 | n/a | def __init__(self, default=None): |
---|
16 | n/a | dict.__init__(self) |
---|
17 | n/a | self.default = default |
---|
18 | n/a | |
---|
19 | n/a | def __getitem__(self, key): |
---|
20 | n/a | try: |
---|
21 | n/a | return dict.__getitem__(self, key) |
---|
22 | n/a | except KeyError: |
---|
23 | n/a | return self.default |
---|
24 | n/a | |
---|
25 | n/a | def get(self, key, *args): |
---|
26 | n/a | if not args: |
---|
27 | n/a | args = (self.default,) |
---|
28 | n/a | return dict.get(self, key, *args) |
---|
29 | n/a | |
---|
30 | n/a | def merge(self, other): |
---|
31 | n/a | for key in other: |
---|
32 | n/a | if key not in self: |
---|
33 | n/a | self[key] = other[key] |
---|
34 | n/a | |
---|
35 | n/a | test_1 = """ |
---|
36 | n/a | |
---|
37 | n/a | Here's the new type at work: |
---|
38 | n/a | |
---|
39 | n/a | >>> print(defaultdict) # show our type |
---|
40 | n/a | <class 'test.test_descrtut.defaultdict'> |
---|
41 | n/a | >>> print(type(defaultdict)) # its metatype |
---|
42 | n/a | <class 'type'> |
---|
43 | n/a | >>> a = defaultdict(default=0.0) # create an instance |
---|
44 | n/a | >>> print(a) # show the instance |
---|
45 | n/a | {} |
---|
46 | n/a | >>> print(type(a)) # show its type |
---|
47 | n/a | <class 'test.test_descrtut.defaultdict'> |
---|
48 | n/a | >>> print(a.__class__) # show its class |
---|
49 | n/a | <class 'test.test_descrtut.defaultdict'> |
---|
50 | n/a | >>> print(type(a) is a.__class__) # its type is its class |
---|
51 | n/a | True |
---|
52 | n/a | >>> a[1] = 3.25 # modify the instance |
---|
53 | n/a | >>> print(a) # show the new value |
---|
54 | n/a | {1: 3.25} |
---|
55 | n/a | >>> print(a[1]) # show the new item |
---|
56 | n/a | 3.25 |
---|
57 | n/a | >>> print(a[0]) # a non-existent item |
---|
58 | n/a | 0.0 |
---|
59 | n/a | >>> a.merge({1:100, 2:200}) # use a dict method |
---|
60 | n/a | >>> print(sortdict(a)) # show the result |
---|
61 | n/a | {1: 3.25, 2: 200} |
---|
62 | n/a | >>> |
---|
63 | n/a | |
---|
64 | n/a | We can also use the new type in contexts where classic only allows "real" |
---|
65 | n/a | dictionaries, such as the locals/globals dictionaries for the exec |
---|
66 | n/a | statement or the built-in function eval(): |
---|
67 | n/a | |
---|
68 | n/a | >>> print(sorted(a.keys())) |
---|
69 | n/a | [1, 2] |
---|
70 | n/a | >>> a['print'] = print # need the print function here |
---|
71 | n/a | >>> exec("x = 3; print(x)", a) |
---|
72 | n/a | 3 |
---|
73 | n/a | >>> print(sorted(a.keys(), key=lambda x: (str(type(x)), x))) |
---|
74 | n/a | [1, 2, '__builtins__', 'print', 'x'] |
---|
75 | n/a | >>> print(a['x']) |
---|
76 | n/a | 3 |
---|
77 | n/a | >>> |
---|
78 | n/a | |
---|
79 | n/a | Now I'll show that defaultdict instances have dynamic instance variables, |
---|
80 | n/a | just like classic classes: |
---|
81 | n/a | |
---|
82 | n/a | >>> a.default = -1 |
---|
83 | n/a | >>> print(a["noway"]) |
---|
84 | n/a | -1 |
---|
85 | n/a | >>> a.default = -1000 |
---|
86 | n/a | >>> print(a["noway"]) |
---|
87 | n/a | -1000 |
---|
88 | n/a | >>> 'default' in dir(a) |
---|
89 | n/a | True |
---|
90 | n/a | >>> a.x1 = 100 |
---|
91 | n/a | >>> a.x2 = 200 |
---|
92 | n/a | >>> print(a.x1) |
---|
93 | n/a | 100 |
---|
94 | n/a | >>> d = dir(a) |
---|
95 | n/a | >>> 'default' in d and 'x1' in d and 'x2' in d |
---|
96 | n/a | True |
---|
97 | n/a | >>> print(sortdict(a.__dict__)) |
---|
98 | n/a | {'default': -1000, 'x1': 100, 'x2': 200} |
---|
99 | n/a | >>> |
---|
100 | n/a | """ |
---|
101 | n/a | |
---|
102 | n/a | class defaultdict2(dict): |
---|
103 | n/a | __slots__ = ['default'] |
---|
104 | n/a | |
---|
105 | n/a | def __init__(self, default=None): |
---|
106 | n/a | dict.__init__(self) |
---|
107 | n/a | self.default = default |
---|
108 | n/a | |
---|
109 | n/a | def __getitem__(self, key): |
---|
110 | n/a | try: |
---|
111 | n/a | return dict.__getitem__(self, key) |
---|
112 | n/a | except KeyError: |
---|
113 | n/a | return self.default |
---|
114 | n/a | |
---|
115 | n/a | def get(self, key, *args): |
---|
116 | n/a | if not args: |
---|
117 | n/a | args = (self.default,) |
---|
118 | n/a | return dict.get(self, key, *args) |
---|
119 | n/a | |
---|
120 | n/a | def merge(self, other): |
---|
121 | n/a | for key in other: |
---|
122 | n/a | if key not in self: |
---|
123 | n/a | self[key] = other[key] |
---|
124 | n/a | |
---|
125 | n/a | test_2 = """ |
---|
126 | n/a | |
---|
127 | n/a | The __slots__ declaration takes a list of instance variables, and reserves |
---|
128 | n/a | space for exactly these in the instance. When __slots__ is used, other |
---|
129 | n/a | instance variables cannot be assigned to: |
---|
130 | n/a | |
---|
131 | n/a | >>> a = defaultdict2(default=0.0) |
---|
132 | n/a | >>> a[1] |
---|
133 | n/a | 0.0 |
---|
134 | n/a | >>> a.default = -1 |
---|
135 | n/a | >>> a[1] |
---|
136 | n/a | -1 |
---|
137 | n/a | >>> a.x1 = 1 |
---|
138 | n/a | Traceback (most recent call last): |
---|
139 | n/a | File "<stdin>", line 1, in ? |
---|
140 | n/a | AttributeError: 'defaultdict2' object has no attribute 'x1' |
---|
141 | n/a | >>> |
---|
142 | n/a | |
---|
143 | n/a | """ |
---|
144 | n/a | |
---|
145 | n/a | test_3 = """ |
---|
146 | n/a | |
---|
147 | n/a | Introspecting instances of built-in types |
---|
148 | n/a | |
---|
149 | n/a | For instance of built-in types, x.__class__ is now the same as type(x): |
---|
150 | n/a | |
---|
151 | n/a | >>> type([]) |
---|
152 | n/a | <class 'list'> |
---|
153 | n/a | >>> [].__class__ |
---|
154 | n/a | <class 'list'> |
---|
155 | n/a | >>> list |
---|
156 | n/a | <class 'list'> |
---|
157 | n/a | >>> isinstance([], list) |
---|
158 | n/a | True |
---|
159 | n/a | >>> isinstance([], dict) |
---|
160 | n/a | False |
---|
161 | n/a | >>> isinstance([], object) |
---|
162 | n/a | True |
---|
163 | n/a | >>> |
---|
164 | n/a | |
---|
165 | n/a | You can get the information from the list type: |
---|
166 | n/a | |
---|
167 | n/a | >>> pprint.pprint(dir(list)) # like list.__dict__.keys(), but sorted |
---|
168 | n/a | ['__add__', |
---|
169 | n/a | '__class__', |
---|
170 | n/a | '__contains__', |
---|
171 | n/a | '__delattr__', |
---|
172 | n/a | '__delitem__', |
---|
173 | n/a | '__dir__', |
---|
174 | n/a | '__doc__', |
---|
175 | n/a | '__eq__', |
---|
176 | n/a | '__format__', |
---|
177 | n/a | '__ge__', |
---|
178 | n/a | '__getattribute__', |
---|
179 | n/a | '__getitem__', |
---|
180 | n/a | '__gt__', |
---|
181 | n/a | '__hash__', |
---|
182 | n/a | '__iadd__', |
---|
183 | n/a | '__imul__', |
---|
184 | n/a | '__init__', |
---|
185 | n/a | '__init_subclass__', |
---|
186 | n/a | '__iter__', |
---|
187 | n/a | '__le__', |
---|
188 | n/a | '__len__', |
---|
189 | n/a | '__lt__', |
---|
190 | n/a | '__mul__', |
---|
191 | n/a | '__ne__', |
---|
192 | n/a | '__new__', |
---|
193 | n/a | '__reduce__', |
---|
194 | n/a | '__reduce_ex__', |
---|
195 | n/a | '__repr__', |
---|
196 | n/a | '__reversed__', |
---|
197 | n/a | '__rmul__', |
---|
198 | n/a | '__setattr__', |
---|
199 | n/a | '__setitem__', |
---|
200 | n/a | '__sizeof__', |
---|
201 | n/a | '__str__', |
---|
202 | n/a | '__subclasshook__', |
---|
203 | n/a | 'append', |
---|
204 | n/a | 'clear', |
---|
205 | n/a | 'copy', |
---|
206 | n/a | 'count', |
---|
207 | n/a | 'extend', |
---|
208 | n/a | 'index', |
---|
209 | n/a | 'insert', |
---|
210 | n/a | 'pop', |
---|
211 | n/a | 'remove', |
---|
212 | n/a | 'reverse', |
---|
213 | n/a | 'sort'] |
---|
214 | n/a | |
---|
215 | n/a | The new introspection API gives more information than the old one: in |
---|
216 | n/a | addition to the regular methods, it also shows the methods that are |
---|
217 | n/a | normally invoked through special notations, e.g. __iadd__ (+=), __len__ |
---|
218 | n/a | (len), __ne__ (!=). You can invoke any method from this list directly: |
---|
219 | n/a | |
---|
220 | n/a | >>> a = ['tic', 'tac'] |
---|
221 | n/a | >>> list.__len__(a) # same as len(a) |
---|
222 | n/a | 2 |
---|
223 | n/a | >>> a.__len__() # ditto |
---|
224 | n/a | 2 |
---|
225 | n/a | >>> list.append(a, 'toe') # same as a.append('toe') |
---|
226 | n/a | >>> a |
---|
227 | n/a | ['tic', 'tac', 'toe'] |
---|
228 | n/a | >>> |
---|
229 | n/a | |
---|
230 | n/a | This is just like it is for user-defined classes. |
---|
231 | n/a | """ |
---|
232 | n/a | |
---|
233 | n/a | test_4 = """ |
---|
234 | n/a | |
---|
235 | n/a | Static methods and class methods |
---|
236 | n/a | |
---|
237 | n/a | The new introspection API makes it possible to add static methods and class |
---|
238 | n/a | methods. Static methods are easy to describe: they behave pretty much like |
---|
239 | n/a | static methods in C++ or Java. Here's an example: |
---|
240 | n/a | |
---|
241 | n/a | >>> class C: |
---|
242 | n/a | ... |
---|
243 | n/a | ... @staticmethod |
---|
244 | n/a | ... def foo(x, y): |
---|
245 | n/a | ... print("staticmethod", x, y) |
---|
246 | n/a | |
---|
247 | n/a | >>> C.foo(1, 2) |
---|
248 | n/a | staticmethod 1 2 |
---|
249 | n/a | >>> c = C() |
---|
250 | n/a | >>> c.foo(1, 2) |
---|
251 | n/a | staticmethod 1 2 |
---|
252 | n/a | |
---|
253 | n/a | Class methods use a similar pattern to declare methods that receive an |
---|
254 | n/a | implicit first argument that is the *class* for which they are invoked. |
---|
255 | n/a | |
---|
256 | n/a | >>> class C: |
---|
257 | n/a | ... @classmethod |
---|
258 | n/a | ... def foo(cls, y): |
---|
259 | n/a | ... print("classmethod", cls, y) |
---|
260 | n/a | |
---|
261 | n/a | >>> C.foo(1) |
---|
262 | n/a | classmethod <class 'test.test_descrtut.C'> 1 |
---|
263 | n/a | >>> c = C() |
---|
264 | n/a | >>> c.foo(1) |
---|
265 | n/a | classmethod <class 'test.test_descrtut.C'> 1 |
---|
266 | n/a | |
---|
267 | n/a | >>> class D(C): |
---|
268 | n/a | ... pass |
---|
269 | n/a | |
---|
270 | n/a | >>> D.foo(1) |
---|
271 | n/a | classmethod <class 'test.test_descrtut.D'> 1 |
---|
272 | n/a | >>> d = D() |
---|
273 | n/a | >>> d.foo(1) |
---|
274 | n/a | classmethod <class 'test.test_descrtut.D'> 1 |
---|
275 | n/a | |
---|
276 | n/a | This prints "classmethod __main__.D 1" both times; in other words, the |
---|
277 | n/a | class passed as the first argument of foo() is the class involved in the |
---|
278 | n/a | call, not the class involved in the definition of foo(). |
---|
279 | n/a | |
---|
280 | n/a | But notice this: |
---|
281 | n/a | |
---|
282 | n/a | >>> class E(C): |
---|
283 | n/a | ... @classmethod |
---|
284 | n/a | ... def foo(cls, y): # override C.foo |
---|
285 | n/a | ... print("E.foo() called") |
---|
286 | n/a | ... C.foo(y) |
---|
287 | n/a | |
---|
288 | n/a | >>> E.foo(1) |
---|
289 | n/a | E.foo() called |
---|
290 | n/a | classmethod <class 'test.test_descrtut.C'> 1 |
---|
291 | n/a | >>> e = E() |
---|
292 | n/a | >>> e.foo(1) |
---|
293 | n/a | E.foo() called |
---|
294 | n/a | classmethod <class 'test.test_descrtut.C'> 1 |
---|
295 | n/a | |
---|
296 | n/a | In this example, the call to C.foo() from E.foo() will see class C as its |
---|
297 | n/a | first argument, not class E. This is to be expected, since the call |
---|
298 | n/a | specifies the class C. But it stresses the difference between these class |
---|
299 | n/a | methods and methods defined in metaclasses (where an upcall to a metamethod |
---|
300 | n/a | would pass the target class as an explicit first argument). |
---|
301 | n/a | """ |
---|
302 | n/a | |
---|
303 | n/a | test_5 = """ |
---|
304 | n/a | |
---|
305 | n/a | Attributes defined by get/set methods |
---|
306 | n/a | |
---|
307 | n/a | |
---|
308 | n/a | >>> class property(object): |
---|
309 | n/a | ... |
---|
310 | n/a | ... def __init__(self, get, set=None): |
---|
311 | n/a | ... self.__get = get |
---|
312 | n/a | ... self.__set = set |
---|
313 | n/a | ... |
---|
314 | n/a | ... def __get__(self, inst, type=None): |
---|
315 | n/a | ... return self.__get(inst) |
---|
316 | n/a | ... |
---|
317 | n/a | ... def __set__(self, inst, value): |
---|
318 | n/a | ... if self.__set is None: |
---|
319 | n/a | ... raise AttributeError("this attribute is read-only") |
---|
320 | n/a | ... return self.__set(inst, value) |
---|
321 | n/a | |
---|
322 | n/a | Now let's define a class with an attribute x defined by a pair of methods, |
---|
323 | n/a | getx() and setx(): |
---|
324 | n/a | |
---|
325 | n/a | >>> class C(object): |
---|
326 | n/a | ... |
---|
327 | n/a | ... def __init__(self): |
---|
328 | n/a | ... self.__x = 0 |
---|
329 | n/a | ... |
---|
330 | n/a | ... def getx(self): |
---|
331 | n/a | ... return self.__x |
---|
332 | n/a | ... |
---|
333 | n/a | ... def setx(self, x): |
---|
334 | n/a | ... if x < 0: x = 0 |
---|
335 | n/a | ... self.__x = x |
---|
336 | n/a | ... |
---|
337 | n/a | ... x = property(getx, setx) |
---|
338 | n/a | |
---|
339 | n/a | Here's a small demonstration: |
---|
340 | n/a | |
---|
341 | n/a | >>> a = C() |
---|
342 | n/a | >>> a.x = 10 |
---|
343 | n/a | >>> print(a.x) |
---|
344 | n/a | 10 |
---|
345 | n/a | >>> a.x = -10 |
---|
346 | n/a | >>> print(a.x) |
---|
347 | n/a | 0 |
---|
348 | n/a | >>> |
---|
349 | n/a | |
---|
350 | n/a | Hmm -- property is builtin now, so let's try it that way too. |
---|
351 | n/a | |
---|
352 | n/a | >>> del property # unmask the builtin |
---|
353 | n/a | >>> property |
---|
354 | n/a | <class 'property'> |
---|
355 | n/a | |
---|
356 | n/a | >>> class C(object): |
---|
357 | n/a | ... def __init__(self): |
---|
358 | n/a | ... self.__x = 0 |
---|
359 | n/a | ... def getx(self): |
---|
360 | n/a | ... return self.__x |
---|
361 | n/a | ... def setx(self, x): |
---|
362 | n/a | ... if x < 0: x = 0 |
---|
363 | n/a | ... self.__x = x |
---|
364 | n/a | ... x = property(getx, setx) |
---|
365 | n/a | |
---|
366 | n/a | |
---|
367 | n/a | >>> a = C() |
---|
368 | n/a | >>> a.x = 10 |
---|
369 | n/a | >>> print(a.x) |
---|
370 | n/a | 10 |
---|
371 | n/a | >>> a.x = -10 |
---|
372 | n/a | >>> print(a.x) |
---|
373 | n/a | 0 |
---|
374 | n/a | >>> |
---|
375 | n/a | """ |
---|
376 | n/a | |
---|
377 | n/a | test_6 = """ |
---|
378 | n/a | |
---|
379 | n/a | Method resolution order |
---|
380 | n/a | |
---|
381 | n/a | This example is implicit in the writeup. |
---|
382 | n/a | |
---|
383 | n/a | >>> class A: # implicit new-style class |
---|
384 | n/a | ... def save(self): |
---|
385 | n/a | ... print("called A.save()") |
---|
386 | n/a | >>> class B(A): |
---|
387 | n/a | ... pass |
---|
388 | n/a | >>> class C(A): |
---|
389 | n/a | ... def save(self): |
---|
390 | n/a | ... print("called C.save()") |
---|
391 | n/a | >>> class D(B, C): |
---|
392 | n/a | ... pass |
---|
393 | n/a | |
---|
394 | n/a | >>> D().save() |
---|
395 | n/a | called C.save() |
---|
396 | n/a | |
---|
397 | n/a | >>> class A(object): # explicit new-style class |
---|
398 | n/a | ... def save(self): |
---|
399 | n/a | ... print("called A.save()") |
---|
400 | n/a | >>> class B(A): |
---|
401 | n/a | ... pass |
---|
402 | n/a | >>> class C(A): |
---|
403 | n/a | ... def save(self): |
---|
404 | n/a | ... print("called C.save()") |
---|
405 | n/a | >>> class D(B, C): |
---|
406 | n/a | ... pass |
---|
407 | n/a | |
---|
408 | n/a | >>> D().save() |
---|
409 | n/a | called C.save() |
---|
410 | n/a | """ |
---|
411 | n/a | |
---|
412 | n/a | class A(object): |
---|
413 | n/a | def m(self): |
---|
414 | n/a | return "A" |
---|
415 | n/a | |
---|
416 | n/a | class B(A): |
---|
417 | n/a | def m(self): |
---|
418 | n/a | return "B" + super(B, self).m() |
---|
419 | n/a | |
---|
420 | n/a | class C(A): |
---|
421 | n/a | def m(self): |
---|
422 | n/a | return "C" + super(C, self).m() |
---|
423 | n/a | |
---|
424 | n/a | class D(C, B): |
---|
425 | n/a | def m(self): |
---|
426 | n/a | return "D" + super(D, self).m() |
---|
427 | n/a | |
---|
428 | n/a | |
---|
429 | n/a | test_7 = """ |
---|
430 | n/a | |
---|
431 | n/a | Cooperative methods and "super" |
---|
432 | n/a | |
---|
433 | n/a | >>> print(D().m()) # "DCBA" |
---|
434 | n/a | DCBA |
---|
435 | n/a | """ |
---|
436 | n/a | |
---|
437 | n/a | test_8 = """ |
---|
438 | n/a | |
---|
439 | n/a | Backwards incompatibilities |
---|
440 | n/a | |
---|
441 | n/a | >>> class A: |
---|
442 | n/a | ... def foo(self): |
---|
443 | n/a | ... print("called A.foo()") |
---|
444 | n/a | |
---|
445 | n/a | >>> class B(A): |
---|
446 | n/a | ... pass |
---|
447 | n/a | |
---|
448 | n/a | >>> class C(A): |
---|
449 | n/a | ... def foo(self): |
---|
450 | n/a | ... B.foo(self) |
---|
451 | n/a | |
---|
452 | n/a | >>> C().foo() |
---|
453 | n/a | called A.foo() |
---|
454 | n/a | |
---|
455 | n/a | >>> class C(A): |
---|
456 | n/a | ... def foo(self): |
---|
457 | n/a | ... A.foo(self) |
---|
458 | n/a | >>> C().foo() |
---|
459 | n/a | called A.foo() |
---|
460 | n/a | """ |
---|
461 | n/a | |
---|
462 | n/a | __test__ = {"tut1": test_1, |
---|
463 | n/a | "tut2": test_2, |
---|
464 | n/a | "tut3": test_3, |
---|
465 | n/a | "tut4": test_4, |
---|
466 | n/a | "tut5": test_5, |
---|
467 | n/a | "tut6": test_6, |
---|
468 | n/a | "tut7": test_7, |
---|
469 | n/a | "tut8": test_8} |
---|
470 | n/a | |
---|
471 | n/a | # Magic test name that regrtest.py invokes *after* importing this module. |
---|
472 | n/a | # This worms around a bootstrap problem. |
---|
473 | n/a | # Note that doctest and regrtest both look in sys.argv for a "-v" argument, |
---|
474 | n/a | # so this works as expected in both ways of running regrtest. |
---|
475 | n/a | def test_main(verbose=None): |
---|
476 | n/a | # Obscure: import this module as test.test_descrtut instead of as |
---|
477 | n/a | # plain test_descrtut because the name of this module works its way |
---|
478 | n/a | # into the doctest examples, and unless the full test.test_descrtut |
---|
479 | n/a | # business is used the name can change depending on how the test is |
---|
480 | n/a | # invoked. |
---|
481 | n/a | from test import support, test_descrtut |
---|
482 | n/a | support.run_doctest(test_descrtut, verbose) |
---|
483 | n/a | |
---|
484 | n/a | # This part isn't needed for regrtest, but for running the test directly. |
---|
485 | n/a | if __name__ == "__main__": |
---|
486 | n/a | test_main(1) |
---|