1 # This contains most of the executable examples from Guido's descr
4 # http://www.python.org/2.2/descrintro.html
6 # A few examples left implicit in the writeup were fleshed out, a few were
7 # skipped due to lack of interest (e.g., faking super() by hand isn't
8 # of much interest anymore), and a few were fiddled to make the output
11 from test
.test_support
import sortdict
14 class defaultdict(dict):
15 def __init__(self
, default
=None):
17 self
.default
= default
19 def __getitem__(self
, key
):
21 return dict.__getitem
__(self
, key
)
25 def get(self
, key
, *args
):
27 args
= (self
.default
,)
28 return dict.get(self
, key
, *args
)
30 def merge(self
, other
):
33 self
[key
] = other
[key
]
37 Here's the new type at work:
39 >>> print defaultdict # show our type
40 <class 'test.test_descrtut.defaultdict'>
41 >>> print type(defaultdict) # its metatype
43 >>> a = defaultdict(default=0.0) # create an instance
44 >>> print a # show the instance
46 >>> print type(a) # show its type
47 <class 'test.test_descrtut.defaultdict'>
48 >>> print a.__class__ # show its class
49 <class 'test.test_descrtut.defaultdict'>
50 >>> print type(a) is a.__class__ # its type is its class
52 >>> a[1] = 3.25 # modify the instance
53 >>> print a # show the new value
55 >>> print a[1] # show the new item
57 >>> print a[0] # a non-existent item
59 >>> a.merge({1:100, 2:200}) # use a dict method
60 >>> print sortdict(a) # show the result
64 We can also use the new type in contexts where classic only allows "real"
65 dictionaries, such as the locals/globals dictionaries for the exec
66 statement or the built-in function eval():
71 >>> print sorted(a.keys())
73 >>> exec "x = 3; print x" in a
75 >>> print sorted(a.keys())
76 [1, 2, '__builtins__', 'x']
81 Now I'll show that defaultdict instances have dynamic instance variables,
82 just like classic classes:
90 >>> 'default' in dir(a)
97 >>> 'default' in d and 'x1' in d and 'x2' in d
99 >>> print sortdict(a.__dict__)
100 {'default': -1000, 'x1': 100, 'x2': 200}
104 class defaultdict2(dict):
105 __slots__
= ['default']
107 def __init__(self
, default
=None):
109 self
.default
= default
111 def __getitem__(self
, key
):
113 return dict.__getitem
__(self
, key
)
117 def get(self
, key
, *args
):
119 args
= (self
.default
,)
120 return dict.get(self
, key
, *args
)
122 def merge(self
, other
):
125 self
[key
] = other
[key
]
129 The __slots__ declaration takes a list of instance variables, and reserves
130 space for exactly these in the instance. When __slots__ is used, other
131 instance variables cannot be assigned to:
133 >>> a = defaultdict2(default=0.0)
140 Traceback (most recent call last):
141 File "<stdin>", line 1, in ?
142 AttributeError: 'defaultdict2' object has no attribute 'x1'
149 Introspecting instances of built-in types
151 For instance of built-in types, x.__class__ is now the same as type(x):
159 >>> isinstance([], list)
161 >>> isinstance([], dict)
163 >>> isinstance([], object)
167 Under the new proposal, the __methods__ attribute no longer exists:
170 Traceback (most recent call last):
171 File "<stdin>", line 1, in ?
172 AttributeError: 'list' object has no attribute '__methods__'
175 Instead, you can get the same information from the list type:
177 >>> pprint.pprint(dir(list)) # like list.__dict__.keys(), but sorted
224 The new introspection API gives more information than the old one: in
225 addition to the regular methods, it also shows the methods that are
226 normally invoked through special notations, e.g. __iadd__ (+=), __len__
227 (len), __ne__ (!=). You can invoke any method from this list directly:
229 >>> a = ['tic', 'tac']
230 >>> list.__len__(a) # same as len(a)
232 >>> a.__len__() # ditto
234 >>> list.append(a, 'toe') # same as a.append('toe')
236 ['tic', 'tac', 'toe']
239 This is just like it is for user-defined classes.
244 Static methods and class methods
246 The new introspection API makes it possible to add static methods and class
247 methods. Static methods are easy to describe: they behave pretty much like
248 static methods in C++ or Java. Here's an example:
254 ... print "staticmethod", x, y
262 Class methods use a similar pattern to declare methods that receive an
263 implicit first argument that is the *class* for which they are invoked.
268 ... print "classmethod", cls, y
271 classmethod test.test_descrtut.C 1
274 classmethod test.test_descrtut.C 1
280 classmethod test.test_descrtut.D 1
283 classmethod test.test_descrtut.D 1
285 This prints "classmethod __main__.D 1" both times; in other words, the
286 class passed as the first argument of foo() is the class involved in the
287 call, not the class involved in the definition of foo().
293 ... def foo(cls, y): # override C.foo
294 ... print "E.foo() called"
299 classmethod test.test_descrtut.C 1
303 classmethod test.test_descrtut.C 1
305 In this example, the call to C.foo() from E.foo() will see class C as its
306 first argument, not class E. This is to be expected, since the call
307 specifies the class C. But it stresses the difference between these class
308 methods and methods defined in metaclasses (where an upcall to a metamethod
309 would pass the target class as an explicit first argument).
314 Attributes defined by get/set methods
317 >>> class property(object):
319 ... def __init__(self, get, set=None):
323 ... def __get__(self, inst, type=None):
324 ... return self.__get(inst)
326 ... def __set__(self, inst, value):
327 ... if self.__set is None:
328 ... raise AttributeError, "this attribute is read-only"
329 ... return self.__set(inst, value)
331 Now let's define a class with an attribute x defined by a pair of methods,
332 getx() and and setx():
336 ... def __init__(self):
342 ... def setx(self, x):
346 ... x = property(getx, setx)
348 Here's a small demonstration:
359 Hmm -- property is builtin now, so let's try it that way too.
361 >>> del property # unmask the builtin
366 ... def __init__(self):
370 ... def setx(self, x):
373 ... x = property(getx, setx)
388 Method resolution order
390 This example is implicit in the writeup.
392 >>> class A: # classic class
394 ... print "called A.save()"
399 ... print "called C.save()"
406 >>> class A(object): # new class
408 ... print "called A.save()"
413 ... print "called C.save()"
427 return "B" + super(B
, self
).m()
431 return "C" + super(C
, self
).m()
435 return "D" + super(D
, self
).m()
440 Cooperative methods and "super"
442 >>> print D().m() # "DCBA"
448 Backwards incompatibilities
452 ... print "called A.foo()"
462 Traceback (most recent call last):
464 TypeError: unbound method foo() must be called with B instance as first argument (got C instance instead)
473 __test__
= {"tut1": test_1
,
482 # Magic test name that regrtest.py invokes *after* importing this module.
483 # This worms around a bootstrap problem.
484 # Note that doctest and regrtest both look in sys.argv for a "-v" argument,
485 # so this works as expected in both ways of running regrtest.
486 def test_main(verbose
=None):
487 # Obscure: import this module as test.test_descrtut instead of as
488 # plain test_descrtut because the name of this module works its way
489 # into the doctest examples, and unless the full test.test_descrtut
490 # business is used the name can change depending on how the test is
492 from test
import test_support
, test_descrtut
493 test_support
.run_doctest(test_descrtut
, verbose
)
495 # This part isn't needed for regrtest, but for running the test directly.
496 if __name__
== "__main__":