Python Classes

Packages are implemented as classes that combine properties (values), methods (functions), and data. An example is the package Numpy.

import numpy as np
print('pi = {0:.10f}'.format(np.pi)) # property: np.pi
print(np.linspace(0,10,11))          # method: np.linspace
 pi = 3.1415926536
 [ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9. 10.]

The following tutorial is an introduction on how to create a Python class with initialization, methods, and properties.

Create a Dog Class

This is an example with a Dog class with instances Tony and Princess.

class Dog:
    def __init__(self,name):
        self.name = name
        self.tricks = []
        return

    def add_trick(self,trick):
        self.tricks.append(trick)
        return

    def show_tricks(self):
        print(self.name+"'s tricks are:")
        for x in self.tricks:
            print(x)

d = Dog('Tony')
d.add_trick('sprint')
d.add_trick('sleep')
d.name = 'Tony2'
d.show_tricks()

e = Dog('Princess')
e.add_trick('sit')
e.add_trick('roll over')
e.eye_color = 'Brown'
e.show_tricks()
Home | Python Classes