Book Image

Sage Beginner's Guide

By : Craig Finch
1 (1)
Book Image

Sage Beginner's Guide

1 (1)
By: Craig Finch

Overview of this book

Table of Contents (17 chapters)
Sage Beginner's Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – creating a vehicle base class


We can avoid duplicating code in related classes by applying the object-oriented principle of inheritance. Inheritance allows a class to be derived from a base class. The derived class inherits the methods and attributes of the base class, and adds its own attributes and methods. This can be rather confusing, so we'll jump into a concrete example. Since tanks, APCs, armored cars, and trucks are all vehicles, we will create a base class for ground vehicles. Then, we will define derived classes to represent various types of vehicles. Enter the following code into a file called vehicle.py :

import sage.all
    
class Cannon():
    
    """Model of a large cannon."""
    
    def __init__(self, damage):
        """Create a Cannon instance
            Arguments:
                damage      Integer that represents
                    the damage inflicted by the cannon
        """
        # _damage   amount of damage inflicted by cannon (integer)
...