Classes and Objects: Bundling Data with Behaviour
A class defines a kind of object, with attributes for its data and methods for its behaviour. Each instance can hold its own state. An initializer sets starting values; access rules require deliberate design.
What a learner can do afterwards
- Define a class with a constructor and two methods, then create two objects from it
- Say what belongs to the object and what belongs to the class
- Rewrite a loose group of variables and functions as one class, and say what improved
1 · Read
__init__ initializes an already-created instance. self refers to that instance. ```python class Account: def __init__(self, balance): self.balance = balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): self.balance -= amount mia = Account(100) sam = Account(40) ```
In obj.area(), Python supplies obj as self. A method returning self.length * self.width multiplies that object's dimensions. With length 3 and width 7, it returns 21.
An instance attribute belongs to one object; a class attribute belongs to the class. Instances read CoffeeOrder.loc unless they shadow it with an instance attribute of the same name. Assigning pet_1.name does not assign pet_2.name. Referenced mutable values may still be shared.
An instance method can update its receiver: ```python def update_max(self, speed): self.max_mph = speed ``` For car.update_max(90.0), self is car. Other cars receive no assignment.
Start CoffeeOrder.cls_id at 0. Each initializer first adds 1 to CoffeeOrder.cls_id, then assigns self.order_id = CoffeeOrder.cls_id. The first two creations receive IDs 1 and 2.
Account groups each balance with deposit and withdraw operations. It does not prevent outside assignment to public attributes. Rejecting invalid withdrawals requires deliberate checks; declaring a class does not supply them.
A class defines shared behaviour. Instances hold attributes, which may reference shared values. __init__ sets initial state; access rules need deliberate design.
Class, attribute and method teaching adapted from OpenStax Introduction to Python Programming, sections 11.1 Object-oriented programming basics, 11.2 Classes and instances and 11.3 Instance methods (CC BY-NC-SA 4.0), openstax.org, with independently written corrections and assessment repairs. · license
The three readings were independently written for this dataset. Video references are to Khan Academy's Classes and objects, Methods and encapsulation and Object composition.
2 · Watch
Take it off screen
Where it sits
8 questions wait behind this lesson, each with its answer explained. Every answer feeds the sky: stars light as they are learned, and dim when it is time to come back.
Start learning this