Python: How To Copy All Attibutes From Base Class To Derived One
Solution 1:
Add a initiator function that copies across the __dict__
attribute:
classSuperMan(SuperHero):
def__init__(self, source=None):
if source isnotNone:
self.__dict__.update(source.__dict__)
The __dict__
of an instance holds all instance attributes, the above merely copies over all of those attributes to the new SuperMan
instance.
Demo:
>>>classSuperHero(object): ...defsetName(self, name):... self.name = name...defgetName(self):...return self.name...>>>classSuperMan(SuperHero): ...def__init__(self, source=None):...if source isnotNone:... self.__dict__.update(source.__dict__)...>>>sh = SuperHero()>>>sh.setName("Clark Kent")>>>sm = SuperMan(sh)>>>print sm.getName()
Clark Kent
Or, for a more terrible hack, you could swap out the class attribute:
sh = SuperHero()
sh.setName("Clark Kent")
sh.__class__ = SuperMan
but that can lead to more interesting bugs as you never called the SuperMan
initializer and thus the expected state might be incorrect.
Solution 2:
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:
classSuperHero(object):@propertydefname(self):
returnself._name
@name.setter
defname(self, name):
self._name = name
sh = SuperHero()
sh.name = "Clark Kent"
Post a Comment for "Python: How To Copy All Attibutes From Base Class To Derived One"