Accessing a method from within its own code
patrick.oloughlin at gmail.com
Mon Nov 2 14:28:02 CET 2009
I was wondering if there was a shorthand way to get a reference to a method
object from within that method's code.
Take this code snippet as an example:
def find_line(self, lines):
if not hasattr(MyClass.do_work, "matcher"):
MyClass.do_work.matcher = re.compile("\d - (.+)")
for line in lines:
m = MyClass.do_work.matcher.match(line)
Here, I have a method which uses a regular expression object to find
matches. I want the regexp object to be tied to the function, but I don't
want to have to recreate it every time the function is called (I am aware
that regexp objects are cached, avoiding this problem, but I'm just using
this as an example for what I want to know), so I've added it to the method
object as an attribute and create it only if it doesn't exist.
However, typing out <Classname>.<MethodName>.<variablename> everytime is
pretty long and susceptible to refactoring issues, so I was wondering if
there was a way in Python that I am missing which allows you to reference
the method that the code is in (like __module__ gives a reference to the
"Ray, when someone asks you if you're a god, you say YES!"
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list