Dictionary of "structs" with functions as components?

Steve Holden sholden at holdenweb.com
Sun Apr 29 15:45:05 EDT 2001


"Eric Sandeen" <eric_sandeen.NO at spam.bigfoot.com> wrote:

> First a disclaimer - I'm pretty new to Python, and OOP is not really my
> bag, so forgive me if this is a silly question...
>
And where else would you ask silly questions? It's a pretty typical beginner
question, but that doesn't make it silly...

> I'm trying to create a data structure which holds information about
> several different filesystems - for example: ext2, reiserfs, and xfs. I'd
> like this to be easily extensible to add other filesystems, as well. The
> type of information I'm including is name, magic number, position of magic
> number in superblock, etc.  So far, I'm doing something like this (these
> values aren't right, just an example) :
>
> FSystems['ext2'].PrettyName = "ext2 filesystem"
> FSystems['ext2'].MagicNo = 0xce32
> FSystems['ext2'].MagicNoPos = 1080
>
> FSystems['xfs'].PrettyName = "XFS filesystem"
> FSystems['xfs'].MagicNo = "XFSB"
> FSystems['xfs'].MagicNoPos = 0
>
> This way I can iterate over FSystems.keys() to do things like check for a
> filesystem, create menus, etc.  These activities are basically the same
> regardless of the filesystem, so they're easy to handle in a single
> function.

Might be better to use a METHOD if it's the same for all objects?
>
> The problem comes when I'd like to define a unique function for each
> filesystem to actually create the filesystem, since this will vary quite a
> bit from fs to fs.  I'd like to access it via something like
>
> FSystems[<fstype>].unique_fs_function()
>
> In C, I'd have a pointer to the function I want.  Is something like this
> possible in Python?
>
Yes. Variables are all pointers in Python, so assuming you've defined

    def doSomethingExt2(args):
        .
        .
        .
you will just be able to say

    FSystems["ext2"].MagicFunction = doSomethingExt2

and similarly for the other filesystem types. Then the call

    FSystems[fstype].MagicFunction(args)

will do what you want. Hope this helps.

regards
 Steve

PS: Of course, later you might want a subclass of some base type for each
filesystem type, then each subclass would have its own unique method instead
of a function, and you'd just call that method (since they could then all
have the same name).




More information about the Python-list mailing list