Classes and objects
So far you've used objects without making your own: strings, lists and dictionaries are all objects, with data and methods bundled together. A class is a blueprint for making your own kind of object.
Class and object
- A class is the blueprint: "a dog has a name and can bark".
- An object (or instance) is one thing built from it: Rex, Bella.
class Dog:
def bark(self):
print("Woof!")
rex = Dog() # create an object (an instance of Dog)
bella = Dog()
rex.bark()
bella.bark()
print(type(rex))Class names use PascalCase: Dog, BankAccount, ShoppingCart.
Objects have their own data
Each object can store its own attributes:
class Dog:
pass # an empty class for now
rex = Dog()
rex.name = "Rex"
rex.age = 3
bella = Dog()
bella.name = "Bella"
bella.age = 5
print(rex.name, rex.age)
print(bella.name, bella.age)Setting attributes from outside like this works, but it's fragile: nothing guarantees every dog has a name. The next lesson's __init__ method fixes that.
Why classes?
Without classes, data about one thing ends up scattered across separate variables and functions that have to be kept in step:
# without a class: three parallel pieces of data
names = ["Asha", "Leo"]
balances = [500, 1200]
def deposit(index, amount):
balances[index] += amount
deposit(0, 100)
print(names[0], balances[0])With a class, the data and the behaviour that belongs to it live together:
class Account:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
asha = Account("Asha", 500)
asha.deposit(100)
print(asha.owner, asha.balance)Don't worry about __init__ and self yet; they're explained next. The point is the shape: each Account carries its own owner and balance, and knows how to deposit into itself.
Everything is an object
print(type(42), type("hi"), type([1, 2]))
print("hello".upper()) # a method of the str class
print((3.5).is_integer()) # even numbers have methods