Source

Adapted from my own handwritten and hand-typed notes from Year 1 to Year 3 of my EEE degree

Definitions

Two linked ideas:

  • Class: a template that defines the attributes (data) and functions (methods) an object will have
  • Object: one instance of a class, holding its own values for those attributes

In Python every variable is an object belonging to a class. The handy built-in classes (int, float, str, list, ...) are called data types for historical reasons.

Example: Sales Employee Record

The class SalesEmployee has attributes name, salary, sales and functions deal_closed, raise_salary.

class SalesEmployee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
        self.sales = 0.0
 
    def deal_closed(self, amount):
        self.sales += amount
 
    def raise_salary(self, pct):
        self.salary *= (1 + pct / 100)
 
amy = SalesEmployee('Amy Alton', 3200.00)
ben = SalesEmployee('Ben Brown', 2950.00)
 
amy.deal_closed(120.00)   # amy.sales -> 120.0
ben.raise_salary(5)       # ben.salary -> 3097.5
print(amy.name, amy.sales)

Key points:

  • objects are created by calling the class like a function
  • member functions act on the object they are called on (amy.deal_closed(...) changes only Amy)
  • attributes are read with dot notation, e.g. ben.salary

Variables

A variable is created the moment it is assigned, for example x = 5. There is no need to declare its data type, Python detects it automatically.

a = 5          # int
b = 2.5        # float
c = 'hello'    # str
type(c)        # <class 'str'>

The built-in numeric types and their operators are in Numeric and Boolean Operations.