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-existant 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 However, our __getitem__() method is not used for variable access by the
84 >>> exec "print foo" in a
85 Traceback (most recent call last):
86 File "<stdin>", line 1, in ?
87 File "<string>", line 1, in ?
88 NameError: name 'foo' is not defined
91 Now I'll show that defaultdict instances have dynamic instance variables,
92 just like classic classes:
100 >>> 'default' in dir(a)
107 >>> 'default' in d and 'x1' in d and 'x2' in d
109 >>> print sortdict(a.__dict__)
110 {'default': -1000, 'x1': 100, 'x2': 200}
114 class defaultdict2(dict):
115 __slots__
= ['default']
117 def __init__(self
, default
=None):
119 self
.default
= default
121 def __getitem__(self
, key
):
123 return dict.__getitem
__(self
, key
)
127 def get(self
, key
, *args
):
129 args
= (self
.default
,)
130 return dict.get(self
, key
, *args
)
132 def merge(self
, other
):
135 self
[key
] = other
[key
]
139 The __slots__ declaration takes a list of instance variables, and reserves
140 space for exactly these in the instance. When __slots__ is used, other
141 instance variables cannot be assigned to:
143 >>> a = defaultdict2(default=0.0)
150 Traceback (most recent call last):
151 File "<stdin>", line 1, in ?
152 AttributeError: 'defaultdict2' object has no attribute 'x1'
159 Introspecting instances of built-in types
161 For instance of built-in types, x.__class__ is now the same as type(x):
169 >>> isinstance([], list)
171 >>> isinstance([], dict)
173 >>> isinstance([], object)
177 Under the new proposal, the __methods__ attribute no longer exists:
180 Traceback (most recent call last):
181 File "<stdin>", line 1, in ?
182 AttributeError: 'list' object has no attribute '__methods__'
185 Instead, you can get the same information from the list type:
187 >>> pprint.pprint(dir(list)) # like list.__dict__.keys(), but sorted
230 The new introspection API gives more information than the old one: in
231 addition to the regular methods, it also shows the methods that are
232 normally invoked through special notations, e.g. __iadd__ (+=), __len__
233 (len), __ne__ (!=). You can invoke any method from this list directly:
235 >>> a = ['tic', 'tac']
236 >>> list.__len__(a) # same as len(a)
238 >>> a.__len__() # ditto
240 >>> list.append(a, 'toe') # same as a.append('toe')
242 ['tic', 'tac', 'toe']
245 This is just like it is for user-defined classes.
250 Static methods and class methods
252 The new introspection API makes it possible to add static methods and class
253 methods. Static methods are easy to describe: they behave pretty much like
254 static methods in C++ or Java. Here's an example:
259 ... print "staticmethod", x, y
260 ... foo = staticmethod(foo)
268 Class methods use a similar pattern to declare methods that receive an
269 implicit first argument that is the *class* for which they are invoked.
273 ... print "classmethod", cls, y
274 ... foo = classmethod(foo)
277 classmethod test.test_descrtut.C 1
280 classmethod test.test_descrtut.C 1
286 classmethod test.test_descrtut.D 1
289 classmethod test.test_descrtut.D 1
291 This prints "classmethod __main__.D 1" both times; in other words, the
292 class passed as the first argument of foo() is the class involved in the
293 call, not the class involved in the definition of foo().
298 ... def foo(cls, y): # override C.foo
299 ... print "E.foo() called"
301 ... foo = classmethod(foo)
305 classmethod test.test_descrtut.C 1
309 classmethod test.test_descrtut.C 1
311 In this example, the call to C.foo() from E.foo() will see class C as its
312 first argument, not class E. This is to be expected, since the call
313 specifies the class C. But it stresses the difference between these class
314 methods and methods defined in metaclasses (where an upcall to a metamethod
315 would pass the target class as an explicit first argument).
320 Attributes defined by get/set methods
323 >>> class property(object):
325 ... def __init__(self, get, set=None):
329 ... def __get__(self, inst, type=None):
330 ... return self.__get(inst)
332 ... def __set__(self, inst, value):
333 ... if self.__set is None:
334 ... raise AttributeError, "this attribute is read-only"
335 ... return self.__set(inst, value)
337 Now let's define a class with an attribute x defined by a pair of methods,
338 getx() and and setx():
342 ... def __init__(self):
348 ... def setx(self, x):
352 ... x = property(getx, setx)
354 Here's a small demonstration:
365 Hmm -- property is builtin now, so let's try it that way too.
367 >>> del property # unmask the builtin
372 ... def __init__(self):
376 ... def setx(self, x):
379 ... x = property(getx, setx)
394 Method resolution order
396 This example is implicit in the writeup.
398 >>> class A: # classic class
400 ... print "called A.save()"
405 ... print "called C.save()"
412 >>> class A(object): # new class
414 ... print "called A.save()"
419 ... print "called C.save()"
433 return "B" + super(B
, self
).m()
437 return "C" + super(C
, self
).m()
441 return "D" + super(D
, self
).m()
446 Cooperative methods and "super"
448 >>> print D().m() # "DCBA"
454 Backwards incompatibilities
458 ... print "called A.foo()"
468 Traceback (most recent call last):
470 TypeError: unbound method foo() must be called with B instance as first argument (got C instance instead)
479 __test__
= {"tut1": test_1
,
488 # Magic test name that regrtest.py invokes *after* importing this module.
489 # This worms around a bootstrap problem.
490 # Note that doctest and regrtest both look in sys.argv for a "-v" argument,
491 # so this works as expected in both ways of running regrtest.
492 def test_main(verbose
=None):
493 # Obscure: import this module as test.test_descrtut instead of as
494 # plain test_descrtut because the name of this module works its way
495 # into the doctest examples, and unless the full test.test_descrtut
496 # business is used the name can change depending on how the test is
498 from test
import test_support
, test_descrtut
499 test_support
.run_doctest(test_descrtut
, verbose
)
501 # This part isn't needed for regrtest, but for running the test directly.
502 if __name__
== "__main__":