In Python, how do you make a subclass from a superclass?
+1
A:
class Class1(object):
pass
class Class2(Class1):
pass
Class2 is a sub-class of Class1
workmad3
2009-10-22 14:28:35
+5
A:
class MySubClass(MySuperClass):
def __init__(self):
MySuperClass.__init__(self)
The section on inheritance in the python documentation explains it in more detail
Bryan Oakley
2009-10-22 14:28:46
You only need to define that `__init__` method if want to add further code to it, otherwise the original init method is used anyway (although it's worth mentioning, and is perfectly valid code)
dbr
2009-10-22 14:37:15
I think the question was vague enough to assume there might be further code added. Better to provide too much info than not enough and end up with another question when the OP implements it. :)
Matt Dewey
2009-10-22 14:50:22
+1
A:
class Mammal(object):
#mammal stuff
class Dog(Mammal):
#doggie stuff
Chris Ballance
2009-10-22 14:28:55
A:
A heroic little example:
class SuperHero(object): #superclass, inherits from default object
def getName(self):
raise NotImplementedError #you want to override this on the child classes
class SuperMan(SuperHero): #subclass, inherits from SuperHero
def getName(self):
return "Clark Kent"
class SuperManII(SuperHero): #another subclass
def getName(self):
return "Clark Kent, Jr."
if __name__ == "__main__":
sm = SuperMan()
print sm.getName()
sm2 = SuperManII()
print sm2.getName()
ewall
2009-10-22 14:39:05
+1
A:
The use of "super" (see Python Built-in, super) may be a slightly better method of calling the parent for initialization:
# Initialize using Parent
#
class MySubClass(MySuperClass):
def __init__(self):
MySuperClass.__init__(self)
# Better initialize using Parent (less redundant).
#
class MySubClassBetter(MySuperClass):
def __init__(self):
super(MySubClassBetter, self).__init__()
thompsongunner
2009-10-22 17:54:40