Python Classes

A Python class is a blueprint for creating objects with similar properties and behaviors. It allows you to define attributes (variables) and methods (functions) that can be associated with the objects created from the class. Classes provide a way to organize and structure code, promoting code reusability and modularity. Here's a simple example of a Python class:

class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

    def perimeter(self):
        return 2 * (self.length + self.width)

The class called Rectangle has two attributes: length and width, which are initialized using the __init__ method (a special method in Python classes that is automatically called when an object is created).

The class also has two methods: area() and perimeter(). The area() method calculates and returns the area of the rectangle by multiplying the length and width attributes. The perimeter() method calculates and returns the perimeter of the rectangle by adding the lengths of all sides. Here's how to create objects from the Rectangle class and use the methods:

# Create a rectangle object with length 5 and width 3
my_rectangle = Rectangle(5, 3)

# Calculate and print the area
print("Area:", my_rectangle.area())

# Calculate and print the perimeter
print("Perimeter:", my_rectangle.perimeter())

Output:

Area: 15
Perimeter: 16

An instance of the Rectangle class called my_rectangle is created with a length of 5 and width of 3. Calling the area() and perimeter() methods on my_rectangle calculates and displays the area and perimeter of the rectangle, respectively.

Python Package as 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()
💬