pythonclassinheritance

Python: How to copy all attibutes from base class to derived one


I want to achieve the following:

#!/usr/bin/python
class SuperHero(object): 
    def setName(self, name):
        self.name = name
    def getName(self):
        return self.name

class SuperMan(SuperHero): 
    pass

if __name__ == "__main__":
    sh = SuperHero()
    sh.setName("Clark Kent")
    sm = SuperMan(sh)  # This does *not* work in real python
    print sm.getName() # prints "Clark Kent"

Do I have to copy the attributes one by one or is there a better way to do it?


Solution

  • I'd prefer explicit solution - copying one by one. Martijn Pieters's solution is nice, but with time your __dict__ may grow and you may not want to copy all it's content (or worse - forget about this fact and experience some nasty side effects). Besides the Zen of Python says: Explicit is better than implicit..

    Side note - you are aware of properties, right? So your code could be more pythonic if you used them:

    class SuperHero(object):
        @property
        def name(self):
            return self._name
        @name.setter
        def name(self, name):
            self._name = name
    
    sh = SuperHero()
    sh.name = "Clark Kent"