Sometimes, when defining a class, the need to refer to this class
arises. One could use the class name, but there is the possibility
that the class name can be bound to a different object later. The
file thisobj.py (download) implements a
bindclass
decorator which, when decorating a method,
binds its first parameter to the class it is defined in.
bindclass
>>> class Foo(Object): ... @bindclass ... def foo(this_class, self): ... return this_class, self ... >>> class Bar(Foo): ... @bindclass ... def bar(this_class, self): ... return this_class, self ... >>> f = Foo() >>> b = Bar() >>> f.foo()(<class '__main__.Foo'>, <__main__.Foo object at 0x61270>)>>> b.foo()(<class '__main__.Foo'>, <__main__.Bar object at 0x56f50>)>>> b.bar()(<class '__main__.Bar'>, <__main__.Bar object at 0x56f50>)>>>
bindfunction
>>> def fac(n): ... if n == 0: ... return 1 ... else: ... return n * fac(n-1) ... >>> fac(10)This can be avoided using the3628800>>> fact = fac >>> fact(10)3628800>>> fac = 'foobar' >>> fact(10)Traceback (most recent call last): File ">>>", line 1, in File " ", line 5, in fac TypeError: 'str' object is not callable
bindfunction
decorator:
>>> @bindfunction ... def factorial(this_function, n): ... if n > 0: ... return n * this_function(n - 1) ... else: ... return 1 ... >>> factorial(15)1307674368000L>>> fac = factorial >>> fac(15)1307674368000L>>> factorial = 'foobar' >>> fac(15)1307674368000L>>>