Python OOP ConceptsGet Certified
What Is Object-Oriented Programming?
Object-oriented programming, usually shortened to OOP, is a way of organizing a program around objects instead of loose variables and functions. An object bundles together the data that describes something, such as a student’s name and GPA, with the actions that can be done with it, such as checking for honors. Real-world things like cars, bank accounts, and players map naturally onto this idea.
So far you have written programs as a sequence of steps with separate functions. That works well for small scripts, but as programs grow, keeping related data and behavior together becomes very valuable. OOP gives you a clear structure, reduces repeated code, and lets several programmers work on different parts of a large program without stepping on each other. Python supports OOP fully, and almost everything you have used, including strings, lists, and dictionaries, is already an object.
- Class: a blueprint that describes what data and behavior a kind of object will have.
- Object (instance): one specific thing built from a class, such as one particular car.
- Attribute: a variable that belongs to an object, such as
nameorbalance. - Method: a function that belongs to a class and works on the object’s data.
- Encapsulation: keeping data protected inside an object and exposing it only through methods.
- Inheritance: creating a new class that reuses and extends an existing class.
- Polymorphism: different classes responding to the same method name in their own way.
- Abstraction: hiding the complicated details so that the user of a class sees only a simple interface.
Classes and Objects
A class is created with the class keyword followed by a name. By convention, class names use CapitalizedWords, such as Student or BankAccount. The class itself is only a plan, like the blueprint of a house, and it does not hold any real data until you build something from it.
Calling the class like a function, as in Student(), creates a new object, which is also called an instance. You can build as many objects from one class as you like, and each one keeps its own separate data. The function isinstance() tells you whether an object was built from a given class.
Try It: Create Your First Object
Click Test My Code to run the program. Then change the name and major to your own.
Student, creates an object from it, gives that object two attributes, prints them, and checks that the object belongs to the class.class Student:
pass
emily = Student()
emily.name = "Emily"
emily.major = "Biology"
print(emily.name, emily.major)
print(isinstance(emily, Student))class Student: creates a new class. The name starts with a capital letter by convention.pass is a placeholder that does nothing. It allows the class to exist without any code inside yet.Student() builds a new object from the class, and the variable emily refers to it.emily.name is set to "Emily".major attribute. Adding attributes one by one like this works, but the next lessons show a tidier way.Emily Biology.isinstance(emily, Student) is True because the object was built from the Student class. The output is True.Attributes and the __init__ Method
Setting attributes after the object exists is easy to forget, so classes usually set them up automatically. A special method named __init__, called the constructor, runs every time a new object is created. Its job is to give the new object its starting data, so every object begins life in a complete, valid state.
The first parameter of every method is self, which stands for the object being worked on. Writing self.make = make stores the value in the object so that it lives on after the method ends. The values you pass when you create the object, such as Car("Ford", "Mustang", 2022), are handed to __init__ as arguments. Two objects from the same class keep completely separate attribute values.
Try It: Build Two Cars
Click Test My Code. Then add a third car of your own.
Car class whose constructor stores a make, a model, and a year, creates two different cars, and prints the attributes of each.class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
car1 = Car("Ford", "Mustang", 2022)
car2 = Car("Chevrolet", "Silverado", 2021)
print(car1.make, car1.model, car1.year)
print(car2.make, car2.model, car2.year)Car is the blueprint for every car object.__init__ runs automatically whenever a new Car is created. self is the new object, and the other parameters receive the values you pass in.self.make = make saves the value on the object as an attribute."Ford", "Mustang", and 2022 are passed to __init__ after self.Ford Mustang 2022.Chevrolet Silverado 2021. Changing one car would never change the other.Methods: Giving Objects Behavior
A method is a function defined inside a class. It always takes self as its first parameter, which gives it access to the object’s attributes. You call a method with a dot, as in acct.deposit(50), and Python passes the object into self automatically, so you never write it yourself.
Methods are what make objects more than just containers of data. A method can read attributes, change them, and return results. Because the data and the code that works on it live together, an object remembers its state between calls. In the example below, each deposit builds on the balance left by the previous one.
Try It: Deposit Money into an Account
Click Test My Code. Then make a second deposit of your own and predict the output first.
Account class with a deposit() method, creates an account for Jackson with $100, makes two deposits, and prints the balance after each one.class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance = self.balance + amount
return self.balance
acct = Account("Jackson", 100)
print(acct.deposit(50))
print(acct.deposit(25))
print(acct.owner, acct.balance)Account describes a simple bank account.balance=0 is a default value, so an account can be opened with no money.deposit is a method. It receives self and the amount to add.balance attribute is increased by the amount.return sends the updated balance back to the caller.acct.deposit(50) adds 50 to 100, so the output is 150.175.Jackson 175.Encapsulation: Protecting Data
Encapsulation means keeping an object’s data safe inside the object and letting the outside world use it only through methods. This protects the data from mistakes, such as spending more cash than a wallet contains. The methods act as guards that check every change before it happens.
Python has no strict private keyword, but it has a strong convention. A name that starts with two underscores, such as __cash, is treated as private: Python quietly renames it inside the class, so code outside the class cannot reach it by the plain name. A single underscore, as in _cash, is a softer signal that means “please do not touch this from outside”. Either way, the goal is the same: control the changes through methods.
Try It: A Wallet That Protects Its Cash
Click Test My Code. Then try spending different amounts to see the guard in action.
Wallet class with a private cash value. The spend() method refuses to overspend, the balance() method reports the cash, and a direct attempt to read the private value fails.class Wallet:
def __init__(self, cash):
self.__cash = cash
def spend(self, amount):
if amount > self.__cash:
return "Not enough cash"
self.__cash = self.__cash - amount
return "Spent $" + str(amount)
def balance(self):
return self.__cash
wallet = Wallet(40)
print(wallet.spend(15))
print(wallet.spend(50))
print(wallet.balance())
try:
print(wallet.__cash)
except AttributeError:
print("Cannot read __cash directly")Wallet will hide its cash from the outside world.__cash private. Python stores it internally under the name _Wallet__cash.spend is the only approved way to take money out.Spent $15.Spent $15.Not enough cash.25.try block lets the program attempt something that might fail.__cash does not exist, so Python raises an AttributeError.except AttributeError: catches that error so the program can continue.Cannot read __cash directly.Inheritance: Reusing Code
Inheritance lets one class build on another. The new class, called the child or subclass, automatically receives every attribute and method of the parent or superclass. You write the shared code once in the parent, and each child adds only what makes it different.
A child class is written with the parent’s name in parentheses: class Teacher(Person):. A child can override a method by defining one with the same name, and it can still call the parent’s version with super(). The relationship is described as “is a”: a Teacher is a Person, so a Teacher can do everything a Person can do and a little more.
Try It: People and Teachers
Click Test My Code. Then create a Coach class of your own that inherits from Person.
Person class with an introduce() method, then a Teacher class that inherits from it, adds a subject, and extends the introduction by calling the parent’s method.class Person:
def __init__(self, name):
self.name = name
def introduce(self):
return "Hi, I'm " + self.name
class Teacher(Person):
def __init__(self, name, subject):
super().__init__(name)
self.subject = subject
def introduce(self):
return super().introduce() + " and I teach " + self.subject
print(Person("Madison").introduce())
print(Teacher("Mr. Carter", "History").introduce())Person holds the code that every kind of person shares.introduce builds a greeting from the person’s name.Hi, I'm followed by the name.Teacher(Person) means that Teacher inherits everything from Person.super().__init__(name) runs the parent’s constructor so the name is stored in the usual way.introduce again in the child replaces the parent’s version for teachers.super().introduce() gets the parent’s greeting, and the child adds the subject to the end.Hi, I'm Madison.Hi, I'm Mr. Carter and I teach History.Polymorphism: One Interface, Many Forms
Polymorphism means “many forms”. It describes the situation in which different kinds of objects respond to the same method name, each in its own way. The code that calls the method does not need to know which kind of object it is dealing with, only that the object has the method.
This makes programs flexible. You can loop over a mixed list of objects and call the same method on each one, and new classes can be added later without changing the loop. Python is happy as long as the object has the right method, a style often described as “duck typing”: if it walks like a duck and quacks like a duck, treat it like a duck.
Try It: College Mascots That Speak
Click Test My Code. Then add a fourth mascot class with its own speak() method.
speak() method, puts one object of each in a list, and calls speak() on every one inside a single loop.class Bulldog:
def speak(self):
return "Woof"
class Longhorn:
def speak(self):
return "Moo"
class Eagle:
def speak(self):
return "Screech"
for mascot in [Bulldog(), Longhorn(), Eagle()]:
print(type(mascot).__name__, "says", mascot.speak())Bulldog represents a mascot such as the one used by many college teams.speak."Woof".Longhorn is a completely separate class.speak, with the same name and the same parameters."Moo".Eagle is another independent class.speak."Screech".type(mascot).__name__ gives the name of the class. The outputs are Bulldog says Woof, Longhorn says Moo, and Eagle says Screech. The same call produced three different behaviors.Class Attributes and Special Methods
Attributes created with self belong to a single object. An attribute written directly in the class body, such as team = "Bulldogs", is a class attribute and is shared by every object of that class. Class attributes are useful for constants and for counters that track how many objects have been created.
Python also lets a class define special methods whose names begin and end with double underscores, often called dunder methods. You have already met __init__. Another is __str__, which controls the text that appears when you print an object. Without it, printing an object shows an unhelpful memory address. A later lesson explores these special methods in depth.
Try It: Count Players on a Team
Click Test My Code. Then create a third player and watch the count change.
Player class with a shared team name and a shared counter, a constructor that increases the counter, and a __str__ method that controls how a player is printed.class Player:
team = "Bulldogs"
count = 0
def __init__(self, name, points):
self.name = name
self.points = points
Player.count = Player.count + 1
def __str__(self):
return self.name + " (" + str(self.points) + " pts) - " + Player.team
liam = Player("Liam", 28)
sophia = Player("Sophia", 34)
print(liam)
print(sophia)
print(Player.count)Player describes a basketball player.team is a class attribute. Every player object shares the same value.count starts at zero and will track how many players have been created.self.name is an instance attribute. It belongs to one player only.Player.count refers to the class attribute, so every new player adds one to the same shared counter.__str__ tells Python what text to show when the object is printed.print() calls __str__. The output is Liam (28 pts) - Bulldogs.Sophia (34 pts) - Bulldogs.2.Using Objects with input()
Objects fit naturally with user input. You read text with input(), convert it to the right types, and pass it to a constructor to create an object. After that, the object’s methods do the thinking, and your main program only has to print the answers. This keeps the rules, such as what counts as an honors student, in one place inside the class.
Remember that input() always returns text, so numbers must be converted with int() or float() before you store them. Putting the rule inside a method also means that you can change it later in one spot, and every part of the program that uses the object gets the update automatically.
Try It: Check Whether a Student Earns Honors
The Program Input box is already filled with one line: Sophia 3.9. Click Run Code straight away, then try another name and a GPA below 3.5.
Student class with an honors() method, reads a name and a GPA from the user, creates an object from them, and prints the GPA and whether the student earns honors.class Student:
def __init__(self, name, gpa):
self.name = name
self.gpa = gpa
def honors(self):
return self.gpa >= 3.5
line = input("Student name and GPA: ")
name, gpa_text = line.split()
student = Student(name, float(gpa_text))
print(student.name, "has a GPA of", student.gpa)
print("Honors:", student.honors())Student stores the data and the rules for one student.honors contains the rule for honors, so it lives with the data it needs.self.gpa >= 3.5 is itself a True or False value, and it is returned directly.input() reads the first line of the Program Input box as one string, such as "Sophia 3.9".split() breaks the text at the space, and the two pieces are unpacked into name and gpa_text. Both are still strings.float(gpa_text) converts the GPA to a number before it is passed to the constructor.Sophia has a GPA of 3.9.student.honors() returns True because 3.9 is at least 3.5. The output is Honors: True.Tip: A helpful way to design a class is to describe it in a sentence: “A Student has a name and a GPA, and can tell whether it earns honors.” The nouns usually become attributes, and the verbs usually become methods.
Common Mistakes with OOP
Object-oriented code introduces a few new rules, and almost every beginner trips over the same handful of them. The error messages are usually clear once you know what to look for. When something fails, check the first line of each method and the line where you create the object.
- Forgetting self:
def deposit(amount):withoutselfraises aTypeError, because Python passes the object as the first argument automatically. - Forgetting self. on attributes: writing
balance = balance + amountinside a method changes a local variable, not the object’s attribute. Writeself.balance. - Forgetting the parentheses:
car = Carstores the class itself, whilecar = Car("Ford", "Mustang", 2022)creates an object. - Misspelling __init__: a name such as
_init_or__int__is not the constructor, so it never runs. - Calling a method on the class:
Account.deposit(50)fails because there is no object. Create an object first, then callacct.deposit(50). - Skipping the parent constructor: a child class that defines
__init__but never callssuper().__init__()does not receive the parent’s attributes. - Sharing a mutable class attribute: a list defined in the class body, such as
items = [], is shared by every object. Create the list inside__init__instead. - Believing private means secret: double underscores only rename an attribute. They are a protection against accidents, not a security feature.
Good Habits for Object-Oriented Design
Good object-oriented code is easy to describe in plain English and easy to change later. A few simple habits keep classes small, clear, and reliable. They also make your programs far easier for other people to read, because they can see at a glance what each class is responsible for.
- Give each class one clear job, and name it with a singular noun in CapitalizedWords, such as
StudentorAccount. - Set up every attribute inside
__init__so objects always start in a complete state. - Keep data private when its value must follow rules, and change it only through methods that check the new value.
- Use inheritance only when the “is a” relationship is true. A Teacher is a Person, but a Car is not an Engine.
- Prefer short, shallow class hierarchies. Deep chains of parents and children are hard to follow.
- Add a
__str__method so that printing an object gives useful information while you debug. - Give methods verb names, such as
deposit()andspend(), and attributes noun names, such asbalance.
Key Takeaways
Object-oriented programming organizes code around objects that carry their own data and behavior. The ideas in this lesson are the foundation for the rest of this section, which looks at classes, constructors, inheritance, polymorphism, and special methods in more detail. Review the points below before moving on.
- A class is a blueprint, and an object is one thing built from it.
- Attributes store an object’s data, and methods define what the object can do.
- The
__init__method sets up a new object, andselfrefers to the object itself. - Encapsulation protects data by exposing it only through methods, and a leading double underscore makes an attribute private.
- Inheritance lets a child class reuse and extend a parent class, and
super()calls the parent’s version of a method. - Polymorphism lets different classes respond to the same method name in their own way.
- Abstraction hides complicated details behind a simple set of methods.
- Class attributes are shared by all objects, and instance attributes belong to one object.
Frequently Asked Questions
Students often find OOP vocabulary confusing at first, because several new words appear at once. The answers below explain the most common questions in plain language, using the same examples you practiced above. Open a question to read the answer, and run the matching example again if you want to see it work.
What is object-oriented programming in Python?
Object-oriented programming is a style of writing programs around objects that bundle data and behavior together. In Python you define a class as a blueprint, create objects from it, store data in attributes, and put actions in methods. Its four main ideas are encapsulation, inheritance, polymorphism, and abstraction.
What is the difference between a class and an object?
A class is the blueprint that describes what attributes and methods something will have. An object, also called an instance, is one actual thing created from that blueprint. One class such as Car can create many objects, and each object keeps its own attribute values.
What does self mean in Python?
self is the first parameter of every instance method, and it refers to the object the method is working on. Python passes it automatically when you write acct.deposit(50). You use self.name and self.balance to read and change the object’s own attributes.
What is the __init__ method?
__init__ is the constructor, a special method that Python runs automatically every time a new object is created. It receives self and any arguments you pass when you create the object, and it is normally used to store the starting values as attributes.
What are the four pillars of OOP?
The four pillars are encapsulation, which keeps data protected inside objects, inheritance, which lets a class reuse another class, polymorphism, which lets different classes respond to the same method name, and abstraction, which hides complicated details behind a simple interface.
What is the difference between a class attribute and an instance attribute?
An instance attribute is created with self inside a method such as __init__, and it belongs to one object. A class attribute is written directly in the class body and is shared by all objects of the class. Use class attributes for constants and for counters.
Does Python have truly private attributes?
No. A name that starts with two underscores, such as __cash, is renamed internally to _ClassName__cash, which prevents accidental access from outside. A single underscore is only a convention. Both are meant to protect against mistakes, not to provide real security.
When should I use OOP instead of plain functions?
Use classes when several pieces of data and the functions that work on them naturally belong together, such as an account with a balance and deposit and withdraw actions, or when you need many similar objects. For short scripts and simple calculations, plain functions are often clearer.