~ubuntu-branches/ubuntu/maverick/python3.1/maverick

« back to all changes in this revision

Viewing changes to Demo/metaclasses/Simple.py

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2009-03-23 00:01:27 UTC
  • Revision ID: james.westby@ubuntu.com-20090323000127-5fstfxju4ufrhthq
Tags: upstream-3.1~a1+20090322
ImportĀ upstreamĀ versionĀ 3.1~a1+20090322

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import types
 
2
 
 
3
class Tracing:
 
4
    def __init__(self, name, bases, namespace):
 
5
        """Create a new class."""
 
6
        self.__name__ = name
 
7
        self.__bases__ = bases
 
8
        self.__namespace__ = namespace
 
9
    def __call__(self):
 
10
        """Create a new instance."""
 
11
        return Instance(self)
 
12
 
 
13
class Instance:
 
14
    def __init__(self, klass):
 
15
        self.__klass__ = klass
 
16
    def __getattr__(self, name):
 
17
        try:
 
18
            value = self.__klass__.__namespace__[name]
 
19
        except KeyError:
 
20
            raise AttributeError(name)
 
21
        if type(value) is not types.FunctionType:
 
22
            return value
 
23
        return BoundMethod(value, self)
 
24
 
 
25
class BoundMethod:
 
26
    def __init__(self, function, instance):
 
27
        self.function = function
 
28
        self.instance = instance
 
29
    def __call__(self, *args):
 
30
        print("calling", self.function, "for", self.instance, "with", args)
 
31
        return self.function(self.instance, *args)
 
32
 
 
33
Trace = Tracing('Trace', (), {})
 
34
 
 
35
class MyTracedClass(Trace):
 
36
    def method1(self, a):
 
37
        self.a = a
 
38
    def method2(self):
 
39
        return self.a
 
40
 
 
41
aninstance = MyTracedClass()
 
42
 
 
43
aninstance.method1(10)
 
44
 
 
45
print(aninstance.method2())