[Courses] [python] Object-oriented programming

Akkana Peck akkana at shallowsky.com
Wed Aug 3 05:25:01 UTC 2011


Prana Peddi writes:
> Hi Akkana,
> 
> I was wondering how to specify inheritance in python - I was planning to use
> vehicles, 2 wheeled vehicles, 4-wheeled vehicles, Bicycles, Cars, Bus,
> Motorcycles for my contrived OOP exercise but was not sure how to specify
> this.

You can make a class inherit from another class like this:

class Two_wheeled_vehicle(Vehicle) :
    ...

class Bicycle(Two_wheeled_vehicle) :

You can do multiple inheritance too:

class Bicycle(Two_wheeled_vehicle, Unpowered_vehicle) :

There are some limitations on it -- see
http://docs.python.org/tutorial/classes.html#multiple-inheritance
To be honest, I haven't used multiple inheritance in Python so
I don't have direct experience with it. (I try to avoid multiple
inheritance in general because it can make code really confusing,
but I know there are times when it's justified.)

> Also, what is the right way to refer to class variables and methods that are
> common for all classes: for eg. count of objects of a particular class? I
> thought that ClassName.classvariable would be the way to go but your class
> notes refer to these are self.classvariable - I thought, class variables
> should have no concept of "self". Can you please clarify?

I agree that Python is confusing in how it handles class static
variables and methods. You're right, a variable like the "line" in
my example doesn't need the "self", and you can say Flashcard.line,
i.e. use the class name to refer to the variable.

Class static functions are harder -- they have a weird syntax that
always makes me suspect this was tacked on long after the language
was designed. There are two types:

class Flashcard :
    line = "==========================="

    @staticmethod
    def print_something(arg1, arg2) :
        print "something"

    @classmethod
    def print_something_with_line(cls, arg1, arg2) :
        print cls.line
        print "something"

The @staticmethod type doesn't have access to class variables like line.
The @classmethod type takes a class as its first argument, then
you can use that to refer to class variables.

The documentation is not very clear:
http://docs.python.org/library/functions.html#classmethod
but you can find some helpful discussions on stackoverflow, like this
one (which I found by googling python @staticmethod @classmethod):
http://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python

	...Akkana


More information about the Courses mailing list