Tuesday, October 11, 2011

[Level 2] How to execute super() in Python

If you want to use parent method in Python,
you could use 'super()' method.
But it only support new style class,
therefore, you need to inherit 'object' class when you create your own class.
e.g.
#!/bin/env python
import os, sys 
 
def new_style():
    class NewSystemTools(object):
        def __init__(self):
            pass
        
        def runCmd(self, sCmd):
            return os.popen(sCmd).read()
     
    class MyNewSystemTools(NewSystemTools):
        def __init__(self):
            pass
        
        def runCmd(self, sCmd):
            return super(MyNewSystemTools, self).runCmd(sCmd)

    print '-- new style --' 
    mnst = MyNewSystemTools()
    print mnst.runCmd('ls /')
 
def old_style(): 
    class SystemTools:
        def __init__(self):
            pass
    
        def runCmd(self, sCmd):
            return os.popen(sCmd).read()
    
    class MySystemTools(SystemTools):
        def __init__(self):
            pass
    
        def runCmd(self, sCmd):
            return super(MySystemTools, self).runCmd(sCmd)
    
    print '-- old style --'
    mst = MySystemTools()
    print mst.runCmd('ls /')
 
new_style()
old_style()


# /tmp/t.py 
-- new style --
bin
boot
cdrom
data
dev
etc
filedb
...
-- old style --
Traceback (most recent call last):
  File "/tmp/t.py", line 17, in 
    print mst.runCmd('ls /')
  File "/tmp/t.py", line 14, in runCmd
    return super(MySystemTools, self).runCmd(sCmd)
TypeError: super() argument 1 must be type, not classobj
Wish this helps. regards, Stanley Huang