ソースを参照

Rejiggered the classes to actually use decorator syntax and commented an explanation on how the @ syntax works. Also wrapped the executing code in a main() function.

Jonathan Reem 12 年 前
コミット
38637e914c
1 ファイル変更30 行追加13 行削除
  1. 30 13
      decorator.py

+ 30 - 13
decorator.py

@@ -1,14 +1,5 @@
 # http://stackoverflow.com/questions/3118929/implementing-the-decorator-pattern-in-python
 
-
-class foo(object):
-    def f1(self):
-        print("original f1")
-
-    def f2(self):
-        print("original f2")
-
-
 class foo_decorator(object):
     def __init__(self, decoratee):
         self._decoratee = decoratee
@@ -20,7 +11,33 @@ class foo_decorator(object):
     def __getattr__(self, name):
         return getattr(self._decoratee, name)
 
-u = foo()
-v = foo_decorator(u)
-v.f1()
-v.f2()
+class undecorated_foo(object):
+    def f1(self):
+        print("original f1")
+
+    def f2(self):
+        print("original f2")
+
+@foo_decorator
+class decorated_foo(object):
+    def f1(self):
+        print("original f1")
+
+    def f2(self):
+        print("original f2")
+
+
+def main():
+    u = undecorated_foo()
+    v = decorated_foo()
+    # This could also be accomplished by:
+    # v = foo_decorator(undecorated_foo)
+    # The @foo_decorator syntax is just shorthand for calling
+    # foo_decorator on the decorated object right after its
+    # declaration.
+
+    v.f1()
+    v.f2()
+
+if __name__ == '__main__':
+    main()