adding methods at runtime and lambda

ici iltchevi at gmail.com
Thu May 3 18:24:10 EDT 2007


On May 3, 10:52 pm, Mike <msu... at comcast.net> wrote:
> I was messing around with adding methods to a class instance at
> runtime and saw the usual code one finds online for this. All the
> examples I saw say, of course, to make sure that for your method that
> you have 'self' as the first parameter. I got to thinking and thought
> "I have a lot of arbitrary methods in several utility files that I
> might like to add to things. How would I do that?" And this is what I
> came up with:
>
> def AddMethod(currObject, method, name = None):
>         if name is None: name = method.func_name
>         class newclass(currObject.__class__):pass
>         setattr(newclass, name, method)
>         return newclass()
>
> And lets say I have a utility function that can check if a drive
> exists on my windows box called HasDrive. I can add that like this:
>
> superdict = addm(dict(), lambda self, d: myUtils.HasDrive(d),
> "hasdrive")
>
> and then I can call
>
> superdict.HasDrive('c')
>
> lambda makes it possible to add any random function because you can
> use it to set self as the first parameter. I've found several real
> uses for this already. My big question is, will something like this be
> possible in python 3000 if lambda really does go away? I've not heard
> much about lambda, reduce, etc. lately but I know Guido wanted them
> out of the language.
>
> Is there a better way to do this today than to use lambda? It seemed
> the simplest way to do this that I could find.

from win32com.client import Dispatch as CreateObject

class HDDs(list):
    def __init__(self):
        fso = CreateObject('Scripting.FileSystemObject')
        for d in fso.Drives:
            if d.DriveType == 2: # Fixed
                list.append(self, d.DriveLetter)

if __name__ == "__main__":
    drv_list = HDDs()
    for d in drv_list:
        print d

    try:
        # Found
        print drv_list.index('P')
    except ValueError:
        # Not Found
        print "P: Not Exists!"




More information about the Python-list mailing list