Python Classes and Objects

Last modified: 
Friday, May 1st, 2015
Topics: 
Python

Basic Class and Subclass Syntax

__metaclass__ = type # use new style classes

class Artist:
    
    def setName(self, name):
        'Set the artist name.' # A doc string callable at Artist.setName.__doc__
        self.name = name
        
    def getName(self):
        return self.name
    
    def introduction(self):
        print "%s is an artist!" % self.name



# Create a subclass for sculptors.
class Sculptor(Artist):
    
    'Sculptor is a subclass of Artist'
    
    def introduction(self):
        'Overrides Artist.introduction()'
        print "%s is a sculptor!" % self.name



artist = Artist() # Create an instance of an artist
artist.setName('Vincent van Gogh') # Set name to Vincent van Gogh
print artist.getName() # Print to screen: Vincent van Gogh
artist.introduction() # Print to screen: Vincent van Gogh is an artist!
print artist.setName.__doc__ # Print to screen: Set the artist name

sculptor = Sculptor()
print sculptor.__doc__ # Print to screen:Sculptor is a subclass of Artist
sculptor.setName('Constantin Brancusi') # Set name to Constantin Brancusi
sculptor.introduction() # Print to screen: Constantin Brancusi is a sculptor!

Multiple Inheritance

class Foo:
    
    def alpha(self):
        print 'One'


class Bar:
    
    def beta(self):
        print 'Two'

        
class Baz:

    def alpha(self):
        print 'Three'


class Qux(Foo, Bar): pass


''' Note Baz will override Foo because it comes first! '''
class Quux(Baz, Foo): pass

Q = Qux()
Q.alpha() # Print to screen: One
Q.beta() # Print to screen: Two

Q2 = Quux()
Q2.alpha() # Print to screen: Three


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.