0% found this document useful (0 votes)
34 views10 pages

Object-Oriented Programming (OOP) in Python 3

Uploaded by

dhanunjayav2007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views10 pages

Object-Oriented Programming (OOP) in Python 3

Uploaded by

dhanunjayav2007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

finished product.

An object contains data, like the raw or preprocessed materials at each step on an
assembly line. In addition, the object contains behavior, like the action that each
— FREE Email Series — assembly line component performs.

🐍 Python Tricks 💌 In this tutorial, you’ll learn how to:

Define a class, which is like a blueprint for creating an object


Use classes to create new objects
Model systems with class inheritance

Note: This tutorial is adapted from the chapter “Object-Oriented Programming


(OOP)” in Python Basics: A Practical Introduction to Python 3.
Email…
The book uses Python’s built-in IDLE editor to create and edit Python files and
interact with the Python shell, so you’ll see occasional references to IDLE
Get Python Tricks » throughout this tutorial. If you don’t use IDLE, you can run the example code
Object-Oriented Programming 🔒 No spam. Unsubscribe any from the editor and environment of your choice.

(OOP) in Python 3 time.


Get Your Code: Click here to download the free sample code that shows you
by David Amos  Sep 11, 2023  108 Comments
how to do object-oriented programming with classes in Python 3.
 intermediate python  Browse Topics
 Guided Learning Paths
Mark as Completed 
What Is Object-Oriented Programming in
 Tweet  Share  Email
 Basics  Intermediate
 Advanced
Python?
Table of Contents api best-practices career
Object-oriented programming is a programming paradigm that provides a means of
community databases data-science
What Is Object-Oriented Programming in Python? structuring programs so that properties and behaviors are bundled into individual
data-structures data-viz devops
How Do You Define a Class in Python? objects.
django docker editors flask
Classes vs Instances
Class Definition front-end gamedev gui For example, an object could represent a person with properties like a name, age,
How Do You Instantiate a Class in Python? machine-learning numpy projects and address and behaviors such as walking, talking, breathing, and running. Or it
Class and Instance Attributes python testing tools web-dev could represent an email with properties like a recipient list, subject, and body and
Instance Methods web-scraping behaviors like adding attachments and sending.
How Do You Inherit From Another Class in Python?
Put another way, object-oriented programming is an approach for modeling
Example: Dog Park
concrete, real-world things, like cars, as well as relations between things, like
Parent Classes vs Child Classes
companies and employees or students and teachers. OOP models real-world entities
Parent Class Functionality Extension
as software objects that have some data associated with them and can perform
Conclusion
certain operations.

Note: You can also check out the Python Basics: Object-Oriented Programming
video course to reinforce the skills that you’ll develop in this section of the
tutorial.
 Remove ads

The key takeaway is that objects are at the center of object-oriented programming in
 Watch NowThis tutorial has a related video course created by the Real Python. In other programming paradigms, objects only represent the data. In OOP,
Python team. Watch it together with the written tutorial to deepen your they additionally inform the overall structure of the program.
understanding: Intro to Object-Oriented Programming (OOP) in Python

Object-oriented programming (OOP) is a method of structuring a program by


bundling related properties and behaviors into individual objects. In this tutorial,
you’ll learn the basics of object-oriented programming in Python.  Remove ads

Conceptually, objects are like the components of a system. Think of a program as a Help
factory assembly line of sorts. At each step of the assembly line, a system
component processes some material, ultimately transforming raw material into a
How Do You Define a Class in Python? Put another way, a class is like a form or questionnaire. An instance is like a form
that you’ve filled out with information. Just like many people can fill out the same
In Python, you define a class by using the class keyword followed by a name and a form with their own unique information, you can create many instances from a
colon. Then you use .__init__() to declare which attributes each instance of the single class.
class should have:

Python Class Definition


class Employee: You start all class definitions with the class keyword, then add the name of the class
def __init__(self, name, age):
and a colon. Python will consider any code that you indent below the class
self.name = name
self.age = age definition as part of the class’s body.

Here’s an example of a Dog class:


But what does all of that mean? And why do you even need classes in the first place?
Take a step back and consider using built-in, primitive data structures as an Python
alternative. # dog.py

Primitive data structures—like numbers, strings, and lists—are designed to represent class Dog:
straightforward pieces of information, such as the cost of an apple, the name of a pass

poem, or your favorite colors, respectively. What if you want to represent something
more complex? The body of the Dog class consists of a single statement: the pass keyword. Python
programmers often use pass as a placeholder indicating where code will eventually
For example, you might want to track employees in an organization. You need to
go. It allows you to run this code without Python throwing an error.
store some basic information about each employee, such as their name, age,
position, and the year they started working.
Note: Python class names are written in CapitalizedWords notation by
One way to do this is to represent each employee as a list: convention. For example, a class for a specific breed of dog, like the Jack
Russell Terrier, would be written as JackRussellTerrier.
Python

kirk = ["James Kirk", 34, "Captain", 2265] The Dog class isn’t very interesting right now, so you’ll spruce it up a bit by defining
spock = ["Spock", 35, "Science Officer", 2254]
some properties that all Dog objects should have. There are several properties that
mccoy = ["Leonard McCoy", "Chief Medical Officer", 2266]
you can choose from, including name, age, coat color, and breed. To keep the
example small in scope, you’ll just use name and age.
There are a number of issues with this approach.
You define the properties that all Dog objects must have in a method called
First, it can make larger code files more difficult to manage. If you reference kirk[0]
.__init__(). Every time you create a new Dog object, .__init__() sets the initial
several lines away from where you declared the kirk list, will you remember that the
state of the object by assigning the values of the object’s properties. That is,
element with index 0 is the employee’s name?
.__init__() initializes each new instance of the class.

Second, it can introduce errors if employees don’t have the same number of
You can give .__init__() any number of parameters, but the first parameter will
elements in their respective lists. In the mccoy list above, the age is missing, so
always be a variable called self. When you create a new class instance, then Python
mccoy[1] will return "Chief Medical Officer" instead of Dr. McCoy’s age.
automatically passes the instance to the self parameter in .__init__() so that
A great way to make this type of code more manageable and more maintainable is to Python can define the new attributes on the object.
use classes.
Update the Dog class with an .__init__() method that creates .name and .age
attributes:
Classes vs Instances Python
Classes allow you to create user-defined data structures. Classes define functions
# dog.py
called methods, which identify the behaviors and actions that an object created
from the class can perform with its data. class Dog:
def __init__(self, name, age):
In this tutorial, you’ll create a Dog class that stores some information about the self.name = name

characteristics and behaviors that an individual dog can have. self.age = age

A class is a blueprint for how to define something. It doesn’t actually contain any Make sure that you indent the .__init__() method’s signature by four spaces, and
data. The Dog class specifies that a name and an age are necessary for defining a the body of the method by eight spaces. This indentation is vitally important. It tells
dog, but it doesn’t contain the name or age of any specific dog. Python that the .__init__() method belongs to the Dog class.

While the class is the blueprint, an instance is an object that’s built from a class and In the body of .__init__(), there are two statements using the self variable:
contains real data. An instance of the Dog class is not a blueprint anymore. It’s an
actual dog with a name, like Miles, who’s four years old.
1. self.name = name creates an attribute called name and assigns the value of the In the output above, you can see that you now have a new Dog object at 0x106702d30.
name parameter to it. This funny-looking string of letters and numbers is a memory address that indicates
2. self.age = age creates an attribute called age and assigns the value of the age where Python stores the Dog object in your computer’s memory. Note that the
parameter to it. address on your screen will be different.

Attributes created in .__init__() are called instance attributes. An instance Now instantiate the Dog class a second time to create another Dog object:
attribute’s value is specific to a particular instance of the class. All Dog objects have a
Python >>>
name and an age, but the values for the name and age attributes will vary depending
on the Dog instance. >>> Dog()
<__main__.Dog object at 0x0004ccc90>

On the other hand, class attributes are attributes that have the same value for all
class instances. You can define a class attribute by assigning a value to a variable The new Dog instance is located at a different memory address. That’s because it’s an
name outside of .__init__(). entirely new instance and is completely unique from the first Dog object that you
created.
For example, the following Dog class has a class attribute called species with the
value "Canis familiaris": To see this another way, type the following:

Python Python >>>

# dog.py >>> a = Dog()


>>> b = Dog()
class Dog: >>> a == b
species = "Canis familiaris" False

def __init__(self, name, age):


self.name = name In this code, you create two new Dog objects and assign them to the variables a and
self.age = age b. When you compare a and b using the == operator, the result is False. Even though a
and b are both instances of the Dog class, they represent two distinct objects in
You define class attributes directly beneath the first line of the class name and memory.
indent them by four spaces. You always need to assign them an initial value. When
you create an instance of the class, then Python automatically creates and assigns
Class and Instance Attributes
class attributes to their initial values.
Now create a new Dog class with a class attribute called .species and two instance
Use class attributes to define properties that should have the same value for every attributes called .name and .age:
class instance. Use instance attributes for properties that vary from one instance to
another. Python >>>

>>> class Dog:


Now that you have a Dog class, it’s time to create some dogs! ... species = "Canis familiaris"
... def __init__(self, name, age):
... self.name = name
... self.age = age
...

 Remove ads
To instantiate this Dog class, you need to provide values for name and age. If you don’t,
then Python raises a TypeError:
How Do You Instantiate a Class in Python?
Python >>>
Creating a new object from a class is called instantiating a class. You can create a
new object by typing the name of the class, followed by opening and closing >>> Dog()
Traceback (most recent call last):
parentheses:
...
TypeError: __init__() missing 2 required positional arguments: 'name' and 'age
Python >>>

>>> class Dog:


... pass To pass arguments to the name and age parameters, put values into the parentheses
... after the class name:
>>> Dog()
<__main__.Dog object at 0x106702d30> Python >>>

>>> miles = Dog("Miles", 4)


You first create a new Dog class with no attributes or methods, and then you >>> buddy = Dog("Buddy", 9)
instantiate the Dog class to create a Dog object.
This creates two new Dog instances—one for a four-year-old dog named Miles and
one for a nine-year-old dog named Buddy.
The Dog class’s .__init__() method has three parameters, so why are you only Instance Methods
passing two arguments to it in the example?
Instance methods are functions that you define inside a class and can only call on
When you instantiate the Dog class, Python creates a new instance of Dog and passes an instance of that class. Just like .__init__(), an instance method always takes
it to the first parameter of .__init__(). This essentially removes the self parameter, self as its first parameter.

so you only need to worry about the name and age parameters.
Open a new editor window in IDLE and type in the following Dog class:

Note: Behind the scenes, Python both creates and initializes a new object Python
when you use this syntax. If you want to dive deeper, then you can read the
# dog.py
dedicated tutorial about the Python class constructor.
class Dog:
species = "Canis familiaris"
After you create the Dog instances, you can access their instance attributes using dot
notation: def __init__(self, name, age):
self.name = name
Python >>>
self.age = age

>>> miles.name
# Instance method
'Miles'
def description(self):
>>> miles.age
return f"{self.name} is {self.age} years old"
4

# Another instance method


>>> buddy.name
def speak(self, sound):
'Buddy'
return f"{self.name} says {sound}"
>>> buddy.age
9

This Dog class has two instance methods:


You can access class attributes the same way:
1. .description() returns a string displaying the name and age of the dog.
Python >>> 2. .speak() has one parameter called sound and returns a string containing the
>>> buddy.species dog’s name and the sound that the dog makes.
'Canis familiaris'
Save the modified Dog class to a file called dog.py and press F5 to run the program.
Then open the interactive window and type the following to see your instance
One of the biggest advantages of using classes to organize data is that instances are
methods in action:
guaranteed to have the attributes you expect. All Dog instances have .species, .name,
and .age attributes, so you can use those attributes with confidence, knowing that Python >>>
they’ll always return a value.
>>> miles = Dog("Miles", 4)

Although the attributes are guaranteed to exist, their values can change >>> miles.description()
dynamically: 'Miles is 4 years old'

Python >>> >>> miles.speak("Woof Woof")


'Miles says Woof Woof'
>>> buddy.age = 10
>>> buddy.age
>>> miles.speak("Bow Wow")
10
'Miles says Bow Wow'

>>> miles.species = "Felis silvestris"


>>> miles.species In the above Dog class, .description() returns a string containing information about
'Felis silvestris'
the Dog instance miles. When writing your own classes, it’s a good idea to have a
method that returns a string containing useful information about an instance of the
In this example, you change the .age attribute of the buddy object to 10. Then you class. However, .description() isn’t the most Pythonic way of doing this.
change the .species attribute of the miles object to "Felis silvestris", which is a
species of cat. That makes Miles a pretty strange dog, but it’s valid Python! When you create a list object, you can use print() to display a string that looks like
the list:
The key takeaway here is that custom objects are mutable by default. An object is
mutable if you can alter it dynamically. For example, lists and dictionaries are Python >>>

mutable, but strings and tuples are immutable. >>> names = ["Miles", "Buddy", "Jack"]
>>> print(names)
['Miles', 'Buddy', 'Jack']

Go ahead and print the miles object to see what output you get:
 Remove ads
Python >>>
How Do You Inherit From Another Class in
>>> print(miles)
<__main__.Dog object at 0x00aeff70>
Python?
Inheritance is the process by which one class takes on the attributes and methods of
When you print miles, you get a cryptic-looking message telling you that miles is a another. Newly formed classes are called child classes, and the classes that you
Dog object at the memory address 0x00aeff70. This message isn’t very helpful. You derive child classes from are called parent classes.
can change what gets printed by defining a special instance method called
You inherit from a parent class by creating a new class and putting the name of the
.__str__().
parent class into parentheses:
In the editor window, change the name of the Dog class’s .description() method to
Python
.__str__():
# inheritance.py
Python
class Parent:
# dog.py hair_color = "brown"

class Dog: class Child(Parent):


# ... pass

def __str__(self):
return f"{self.name} is {self.age} years old" In this minimal example, the child class Child inherits from the parent class Parent.
Because child classes take on the attributes and methods of parent classes,
Save the file and press F5 . Now, when you print miles, you get a much friendlier Child.hair_color is also "brown" without your explicitly defining that.

output:
Note: This tutorial is adapted from the chapter “Object-Oriented Programming
Python >>>
(OOP)” in Python Basics: A Practical Introduction to Python 3. If you enjoy what
>>> miles = Dog("Miles", 4) you’re reading, then be sure to check out the rest of the book and the learning
>>> print(miles) path.
'Miles is 4 years old'

You can also check out the Python Basics: Building Systems With Classes video
Methods like .__init__() and .__str__() are called dunder methods because they course to reinforce the skills that you’ll develop in this section of the tutorial.
begin and end with double underscores. There are many dunder methods that you
can use to customize classes in Python. Understanding dunder methods is an Child classes can override or extend the attributes and methods of parent classes. In
important part of mastering object-oriented programming in Python, but for your other words, child classes inherit all of the parent’s attributes and methods but can
first exploration of the topic, you’ll stick with these two dunder methods. also specify attributes and methods that are unique to themselves.

Although the analogy isn’t perfect, you can think of object inheritance sort of like
Note: Check out When Should You Use .__repr__() vs .__str__() in Python? to
genetic inheritance.
learn more about .__str__() and its cousin .__repr__().
You may have inherited your hair color from your parents. It’s an attribute that you
If you want to reinforce your understanding with a practical exercise, then you can were born with. But maybe you decide to color your hair purple. Assuming that your
click on the block below and work on solving the challenge: parents don’t have purple hair, you’ve just overridden the hair color attribute that
you inherited from your parents:

Exercise: Create a Car Class Show/Hide Python

# inheritance.py
When you’re done with your own implementation of the challenge, then you can
expand the block below to see a possible solution: class Parent:
hair_color = "brown"

Solution: Create a Car Class Show/Hide class Child(Parent):


hair_color = "purple"

When you’re ready, you can move on to the next section. There, you’ll see how to
If you change the code example like this, then Child.hair_color will be "purple".
take your knowledge one step further and create classes from other classes.
You also inherit, in a sense, your language from your parents. If your parents speak
English, then you’ll also speak English. Now imagine you decide to learn a second
language, like German. In this case, you’ve extended your attributes because you’ve
added an attribute that your parents don’t have:
 Remove ads
Python Python >>>

# inheritance.py >>> buddy.speak("Yap")


'Buddy says Yap'
class Parent:
speaks = ["English"] >>> jim.speak("Woof")
'Jim says Woof'
class Child(Parent):
def __init__(self): >>> jack.speak("Woof")
super().__init__() 'Jack says Woof'
self.speaks.append("German")

Passing a string to every call to .speak() is repetitive and inconvenient. Moreover,


You’ll learn more about how the code above works in the sections below. But before the .breed attribute should determine the string representing the sound that each
you dive deeper into inheritance in Python, you’ll take a walk to a dog park to better Dog instance makes, but here you have to manually pass the correct string to
understand why you might want to use inheritance in your own code. .speak() every time you call it.

You can simplify the experience of working with the Dog class by creating a child
Example: Dog Park class for each breed of dog. This allows you to extend the functionality that each
Pretend for a moment that you’re at a dog park. There are many dogs of different child class inherits, including specifying a default argument for .speak().
breeds at the park, all engaging in various dog behaviors.

Suppose now that you want to model the dog park with Python classes. The Dog
class that you wrote in the previous section can distinguish dogs by name and age
but not by breed.  Remove ads

You could modify the Dog class in the editor window by adding a .breed attribute:
Parent Classes vs Child Classes
Python
In this section, you’ll create a child class for each of the three breeds mentioned
# dog.py above: Jack Russell terrier, dachshund, and bulldog.

class Dog:
For reference, here’s the full definition of the Dog class that you’re currently working
species = "Canis familiaris"
with:
def __init__(self, name, age, breed):
Python
self.name = name
self.age = age # dog.py
self.breed = breed

class Dog:
def __str__(self): species = "Canis familiaris"
return f"{self.name} is {self.age} years old"

def __init__(self, name, age):


def speak(self, sound): self.name = name
return f"{self.name} says {sound}" self.age = age

def __str__(self):
Press F5 to save the file. Now you can model the dog park by creating a bunch of
return f"{self.name} is {self.age} years old"
different dogs in the interactive window:
def speak(self, sound):
Python >>> return f"{self.name} says {sound}"

>>> miles = Dog("Miles", 4, "Jack Russell Terrier")


>>> buddy = Dog("Buddy", 9, "Dachshund")
After doing the dog park example in the previous section, you’ve removed .breed
>>> jack = Dog("Jack", 3, "Bulldog")
again. You’ll now write code to keep track of a dog’s breed using child classes
>>> jim = Dog("Jim", 5, "Bulldog")
instead.

Each breed of dog has slightly different behaviors. For example, bulldogs have a low To create a child class, you create a new class with its own name and then put the
bark that sounds like woof, but dachshunds have a higher-pitched bark that sounds name of the parent class in parentheses. Add the following to the dog.py file to
more like yap. create three new child classes of the Dog class:

Using just the Dog class, you must supply a string for the sound argument of .speak()
every time you call it on a Dog instance:
Python Python >>>

# dog.py >>> isinstance(miles, Bulldog)


False
# ...
>>> isinstance(jack, Dachshund)
class JackRussellTerrier(Dog): False
pass

class Dachshund(Dog): More generally, all objects created from a child class are instances of the parent
pass class, although they may not be instances of other child classes.

class Bulldog(Dog): Now that you’ve created child classes for some different breeds of dogs, you can
pass
give each breed its own sound.

Press F5 to save and run the file. With the child classes defined, you can now
create some dogs of specific breeds in the interactive window:

Python >>>  Remove ads

>>> miles = JackRussellTerrier("Miles", 4)


>>> buddy = Dachshund("Buddy", 9)
>>> jack = Bulldog("Jack", 3)
Parent Class Functionality Extension
>>> jim = Bulldog("Jim", 5) Since different breeds of dogs have slightly different barks, you want to provide a
default value for the sound argument of their respective .speak() methods. To do
Instances of child classes inherit all of the attributes and methods of the parent this, you need to override .speak() in the class definition for each breed.
class:
To override a method defined on the parent class, you define a method with the
Python >>> same name on the child class. Here’s what that looks like for the JackRussellTerrier
>>> miles.species class:
'Canis familiaris'
Python
>>> buddy.name
# dog.py
'Buddy'

# ...
>>> print(jack)
Jack is 3 years old
class JackRussellTerrier(Dog):
def speak(self, sound="Arf"):
>>> jim.speak("Woof")
return f"{self.name} says {sound}"
'Jim says Woof'

# ...

To determine which class a given object belongs to, you can use the built-in type():
Now .speak() is defined on the JackRussellTerrier class with the default argument
Python >>>
for sound set to "Arf".
>>> type(miles)
<class '__main__.JackRussellTerrier'> Update dog.py with the new JackRussellTerrier class and press F5 to save and run
the file. You can now call .speak() on a JackRussellTerrier instance without passing
What if you want to determine if miles is also an instance of the Dog class? You can do an argument to sound:
this with the built-in isinstance():
Python >>>

Python >>> >>> miles = JackRussellTerrier("Miles", 4)


>>> miles.speak()
>>> isinstance(miles, Dog)
'Miles says Arf'
True

Sometimes dogs make different noises, so if Miles gets angry and growls, you can
Notice that isinstance() takes two arguments, an object and a class. In the example
still call .speak() with a different sound:
above, isinstance() checks if miles is an instance of the Dog class and returns True.
Python >>>
The miles, buddy, jack, and jim objects are all Dog instances, but miles isn’t a Bulldog
instance, and jack isn’t a Dachshund instance: >>> miles.speak("Grrr")
'Miles says Grrr'
One thing to keep in mind about class inheritance is that changes to the parent class Update dog.py with the new JackRussellTerrier class. Save the file and press F5
automatically propagate to child classes. This occurs as long as the attribute or so you can test it in the interactive window:
method being changed isn’t overridden in the child class.
Python >>>

For example, in the editor window, change the string returned by .speak() in the Dog >>> miles = JackRussellTerrier("Miles", 4)
class: >>> miles.speak()
'Miles barks: Arf'
Python

# dog.py Now when you call miles.speak(), you’ll see output reflecting the new formatting in
the Dog class.
class Dog:
# ...
Note: In the above examples, the class hierarchy is very straightforward. The
def speak(self, sound):
JackRussellTerrier class has a single parent class, Dog. In real-world examples,
return f"{self.name} barks: {sound}"
the class hierarchy can get quite complicated.
# ...
The super() function does much more than just search the parent class for a
method or an attribute. It traverses the entire class hierarchy for a matching
Save the file and press F5 . Now, when you create a new Bulldog instance named
method or attribute. If you aren’t careful, super() can have surprising results.
jim, jim.speak() returns the new string:

Python >>> If you want to check your understanding of the concepts that you learned about in
this section with a practical exercise, then you can click on the block below and
>>> jim = Bulldog("Jim", 5)
>>> jim.speak("Woof") work on solving the challenge:
'Jim barks: Woof'

Exercise: Class Inheritance Show/Hide


However, calling .speak() on a JackRussellTerrier instance won’t show the new
style of output:
When you’re done with your own implementation of the challenge, then you can
Python >>> expand the block below to see a possible solution:

>>> miles = JackRussellTerrier("Miles", 4)


>>> miles.speak() Solution: Class Inheritance Show/Hide
'Miles says Arf'

Sometimes it makes sense to completely override a method from a parent class. But
Nice work! In this section, you’ve learned how to override and extend methods from Table of Contents
a parent class, and you worked on a small practical example to cement your new
in this case, you don’t want the JackRussellTerrier class to lose any changes that What Is Object-Oriented
skills. Programming in Python?
you might make to the formatting of the Dog.speak() output string.
How Do You Define a Class in
To do this, you still need to define a .speak() method on the child Python?
JackRussellTerrier class. But instead of explicitly defining the output string, you How Do You Instantiate a Class in
need to call the Dog class’s .speak() from inside the child class’s .speak() using the Python?
 Remove ads How Do You Inherit From Another
same arguments that you passed to JackRussellTerrier.speak().
Class in Python?
You can access the parent class from inside a method of a child class by using
super():
Conclusion → Conclusion

In this tutorial, you learned about object-oriented programming (OOP) in Python.


Python
Most modern programming languages, such as Java, C#, and C++, follow OOP Mark as Completed 
# dog.py principles, so the knowledge that you gained here will be applicable no matter
where your programming career takes you.
# ...

In this tutorial, you learned how to:  Tweet  Share  Email


class JackRussellTerrier(Dog):
def speak(self, sound="Arf"):
Define a class, which is a sort of blueprint for an object
return super().speak(sound)
 Recommended Video Course
Instantiate a class to create an object
# ... Intro to Object-Oriented
Use attributes and methods to define the properties and behaviors of an
Programming (OOP) in Python
object
When you call super().speak(sound) inside JackRussellTerrier, Python searches the Use inheritance to create child classes from a parent class
parent class, Dog, for a .speak() method and calls it with the variable sound.
Reference a method on a parent class using super()
Check if an object inherits from another class using isinstance()
If you enjoyed what you learned in this sample from Python Basics: A Practical
Introduction to Python 3, then be sure to check out the rest of the book and check
out our introduction to Python learning path. Aldren Geir Arne Joanna

 Take the Quiz: Test your knowledge with our interactive “Object-Oriented
Programming (OOP) in Python 3” quiz. Upon completion you will receive a
score so you can track your learning progress over time:
Jacob Kate Martin
Take the Quiz »

Mark as Completed 

 Watch Now This tutorial has a related video course created by the Real
Master Real-World Python Skills
Python team. Watch it together with the written tutorial to deepen your With Unlimited Access to Real Python
understanding: Intro to Object-Oriented Programming (OOP) in Python

🐍 Python Tricks 💌
Get a short & sweet Python Trick delivered to your inbox every couple of
days. No spam ever. Unsubscribe any time. Curated by the Real Python
team.

Join us and get access to thousands of


tutorials, hands-on video courses, and
a community of expert Pythonistas:

Level Up Your Python Skills »

Email Address

Send Me Python Tricks »


What Do You Think?

Rate this article:


About David Amos  Tweet  Share  Share  Email

What’s your #1 takeaway or favorite thing you learned? How are you going to
David is a writer, programmer, and mathematician passionate about exploring mathematics
put your newfound skills to use? Leave a comment below and let us know.
through code.

» More about David Commenting Tips: The most useful comments are those written with the
goal of learning from or helping out other students. Get tips for asking
good questions and get answers to common questions in our support
portal.

Looking for a real-time conversation? Visit the Real Python Community


Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!
worked on this tutorial are:

Keep Learning
Related Tutorial Categories: intermediate python

Recommended Video Course: Intro to Object-Oriented Programming (OOP) in


Python

 Remove ads

© 2012–2023 Real Python ⋅ Newsletter ⋅ Podcast ⋅ YouTube ⋅ Twitter ⋅ Facebook ⋅ Instagram ⋅


Python Tutorials ⋅ Search ⋅ Privacy Policy ⋅ Energy Policy ⋅ Advertise ⋅ Contact
❤️ Happy Pythoning!

You might also like