[tutor] Dumb subclassing question
Kent Johnson
kent_johnson at skillsoft.com
Thu Aug 5 17:58:58 CEST 2004
At 04:12 PM 8/5/2004 +0100, Andy Baker wrote:
>Your idea below is some spooky voodoo! It would be way beyond my ability to
>do so but your black magic could surely be wrapped in a general metaclass
>type thing and given a nice syntax? On second thoughts I am sooooo running
>before I can walk ;-)
I'm over my head too. I'm amazed that this is possible :-)
Since my solution modifies the (only) path class object, it can go in the
module that defines the subclass, and then be applied behind the scenes for
all users.
#######################################
# MyPath.py
from path import path
class MyPath(path):
def coolStuff(self):
print 'It works!'
# Remember the old __new__ so we can delegate to it
originalNew = path.__new__
# This is going to be the new path.__new__. It will return an instance of
MyPath
def newNew(cls, *args, **kwds):
return originalNew(MyPath, *args, **kwds)
# Replace path.__new__ with our new version
path.__new__ = staticmethod(newNew)
#################################
# MyPathClient.py
from MyPath import MyPath
# Try it out
p = MyPath("C:")
print type(p)
p.coolStuff()
f = p.files()[0]
print f
print type(f)
f.coolStuff()
prints:
<class 'MyPath.MyPath'>
It works!
C:.DS_Store
<class 'MyPath.MyPath'>
It works!
More information about the Tutor
mailing list