callbacks within classes
Ken Seehof
kens at sightreader.com
Mon Apr 2 19:12:32 EDT 2001
How about:
class FileManager:
def __init__(self):
self.path = << some path >>
self.rs = << a record set >>
def InsertDirectories(self):
os.path.walk(self.path, self.InsertDirectory, self.rs)
def InsertDirectory(self, rs, dirname, names):
...
It looks like InsertDirectory takes 4 args, which it does, sort of,
but not really.
Um. Let me start over.
self.InsertDirectory is a bound method. That means it behaves
like a function taking 3 arguments, (not 4). The first arg (self) is
implied.
In other words,
def InsertDirectory(self, rs, dirname, names)
... means you get the rather convenient signature:
self.InsertDirectory(rs, dirname, names)
which is what you want.
Just try it. You'll see. :-)
----- Original Message -----
From: "Adrian Graham" <aag at stanford.edu>
Newsgroups: comp.lang.python
To: <python-list at python.org>
Sent: Monday, April 02, 2001 3:22 PM
Subject: callbacks within classes
> I'm in the process of writing a class based on a module that I have
> previously written. The problem that I'm running across is that since
"self"
> is always the first argument to any function within a class, functions
that
> I have been using as callbacks no longer work since their signature has
> changed to include self.
>
> For instance, what I used to code as this:
>
> def InsertDirectories():
> os.path.walk(path, InsertDirectory, rs)
>
> def InsertDirectory(rs, dirname, names):
> ...
>
> I'd like to code as this:
>
> class FileManager:
>
> def __init__(self):
> self.path = << some path >>
> self.rs = << a record set >>
>
> def InsertDirectories(self):
> os.path.walk(self.path, self.InsertDirectory, self.rs)
>
> def InsertDirectory(rs, dirname, names):
> ...
>
> Unfortunately, I can't code it this way, since InsertDirectory's signature
> is now: InsertDirectory(self, rs, dirname, names), which doesn't match
> os.path.walk's callback signature. I know the easy (and inelegant) way to
> fix this problem is to simply move InsertDirectory outside of the class.
> This doesn't really make sense to me since the functionality really should
> be contained within the class.
>
> I have the feeling that there is some elegant way to do what I want with
> Python, but that my C++/Java experience is getting in the way. Any
> suggestions?
>
> Thanks,
>
> Adrian
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list