tags:

views:

358

answers:

8

In Python, how do you make a subclass from a superclass?

A: 
class Subclass (SuperClass):
      # Subclass stuff here
iWerner
+1  A: 
class Class1(object):
    pass

class Class2(Class1):
    pass

Class2 is a sub-class of Class1

workmad3
+2  A: 

You use:

class DerivedClassName(BaseClassName):

For details, see the Python docs, section 9.5.

Reed Copsey
+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
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
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
+1  A: 
class Mammal(object): 
#mammal stuff

class Dog(Mammal): 
#doggie stuff
Chris Ballance
The question is tagged with Python...
dbr
Question was not tagged when I answered it...
Chris Ballance
Updated to Python per OP's additional clarification
Chris Ballance
A: 

Subclassing in Python is done as follows:

class WindowElement:
    def print(self):
        pass

class Button(WindowElement):
    def print(self):
        pass

Here is a tutorial about Python that also contains classes and subclasses.

dmeister
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
+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