Skip to content

Object Oriented Programming in Python

BK Jackson edited this page Oct 12, 2019 · 7 revisions

Inheritance

class Line(object):
    def __init__(self, c0, c1):
        self.c0 = c0
        self.c1 = c1

    def __call__(self, x):
        return self.c0 + self.c1*x

    def table(self, L, R, n):
        """Return a table with n points for L <= x <= R."""
        s = ''
        import numpy as np
        for x in np.linspace(L, R, n):
            y = self(x)
            s += '%12g %12g\n' % (x, y)
        return s

class Parabola(Line):
    """
    Adding only the code that we need for a parabola that is not 
    already written for class Line.
    """
    def __init__(self, c0, c1, c2):
        Line.__init__(self, c0, c1)  # let Line store c0 and c1
        self.c2 = c2

    def __call__(self, x):
        return Line.__call__(self, x) + self.c2*x**2

Source

Calling a method in the superclass

Line.methodname(self, arg1, arg2, ...)
# or
super(Parabola, self).methodname(arg1, arg2, ...)

Source

OOP in Python

Introduction to Classes in Python - By Hans Petter Langtangen, Jun. 14, 2016. Has a focus on scientific programming with Python.
Object-Oriented Programming in Python - By Hans Petter Langtangen, Jun. 14, 2016.
Python Practice Book Lean, simple book. Includes OOP and functional programming.
Improve Your Python: Python Classes and Object Oriented Programming Good summary in one webpage. By Jeff Knupp.
Intro to OOP in Python 3
Zetcode OOP Python Tutorial
OOP Python - Tutorials Point
Python 3 Course: OOP - python-course.eu, one of the best imho

Clone this wiki locally