arrow-left

All pages
gitbookPowered by GitBook
1 of 3

Loading...

Loading...

Loading...

Classes

Python Classes and Interfaces

As an object-oriented programming language, Python supports a full range of features, such as inheritance, polymorphism, and encapsulation. Getting things done in Python often requires writing new classes and defining how they interact through their interfaces and hierarchies.

Python's classes and inheritance make it easy to express a program's intended behaviors with objects. They allow you to improve and expand functionality over time. They provide flexibility in an environment of changing requirements. Knowing how to use them well enables you to write maintainable code.

hashtag
Item 37: Compose Classes Instead of Nesting Many Levels of Built-in Types

Python's built-in dictionary type is wonderful for maintaining dynamic internal state over the lifetime of an object. By dynamic, I mean situations in which you need to do bookkeeping for an unexpected set of identifiers. For example, say that I want to record the grades of a set of students whose names aren't known in advance. I can define a class to store the names in a dictionary instead of using a predefined attribute for each student:

Dictionaries and their related built-in types are so easy to use that there's a danger of overextending them to write brittle code. For example, say that I want to extend the SimpleGradebook class to keep a list of grades by subject, not just overall. I can do this by changing the _grades dictionary to map student names (its keys) to yet another dictionary (its values). The innermost dictionary will map subjects (its keys) to a list of grades (its values). Here, I do this by using a defaultdict instance for the inner dictionary to handle missing subjects (see Item 17: "Prefer defaultdict Over setdefault to Handle Miss ing Items in Internal State" for background):

Python Objects & Classes

hashtag
Creating object and classes #

Python is an object-oriented language. In python everything is object i.e int, str, bool even modules, functions are also objects.

Object oriented programming use objects to create programs, and these objects stores data and behaviours.

hashtag
Defining class #

Class name in python is preceded with class keyword followed by a colon (:). Classes commonly contains data field to store the data and methods for defining behaviors. Also every class in python contains a special method called initializer (also commonly known as constructors), which get invoked automatically every time new object is created.

Let's see an example.

Here we have created a class called Person which contains one data field called name and method whoami().

hashtag
What is self? #

All methods in python including some special methods like initializer have first parameter self. This parameter refers to the object which invokes the method. When you create new object the self parameter in the __init__ method is automatically set to reference the object you have just created.

hashtag
Creating object from class #

Expected Output:

note:

When you call a method you don't need to pass anything to self parameter, python automatically does that for you behind the scenes.

You can also change the name data field.

Expected Output:

Although it is a bad practice to give access to your data fields outside the class. We will discuss how to prevent this next.

hashtag
Hiding data fields #

To hide data fields you need to define private data fields. In python you can create private data field using two leading underscores. You can also define a private method using two leading underscores.

Let's see an example

Expected Output:

Let's try to access __balance data field outside of class.

Expected Output:

AttributeError: 'BankAccount' object has no attribute '__balance'

As you can see, now the __balance field is not accessible outside the class.

In next chapter we will learn about operator overloadingarrow-up-right.

Other Tutorials (Sponsors)

This site generously supported by DataCamparrow-up-right. DataCamp offers online interactive Python Tutorialsarrow-up-right for Data Science. Join over a million other learners and get started learning Python for data science today!

Sourcearrow-up-right

class SimpleGradebook:
    def __init__(self):
        self._grades = {}
    def add_student(self, name):
        self._grades[name] = []
    def report_grade(self, name, score):
        self._grades[name].append(score)

   def average_grade(self, name):
        grades = self._grades[name]
        return sum(grades) / len(grades)
book = SimpleGradebook()
book.add_student('Isaac Newton')
book.report_grade('Isaac Newton', 90)
book.report_grade('Isaac Newton', 95)
book.report_grade('Isaac Newton', 85)
print(book.average_grade('Isaac Newton'))
>>>
90.0

index

Creating object and classes # Python is an object-oriented language. In python everything is object i.e int, str, bool even modules, functions are al…

Python Object and Classes

(Sponsors) Get started learning Python with DataCamp'sarrow-up-right free Intro to Python tutorialarrow-up-right. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!arrow-up-right

Updated on Jan 07, 2020

hashtag
Creating object and classes #

Python is an object-oriented language. In python everything is object i.e int, str, bool even modules, functions are also objects.

Object oriented programming use objects to create programs, and these objects stores data and behaviours.

hashtag
Defining class #

Class name in python is preceded with class keyword followed by a colon (:). Classes commonly contains data field to store the data and methods for defining behaviors. Also every class in python contains a special method called initializer (also commonly known as constructors), which get invoked automatically every time new object is created.

Let's see an example.

Here we have created a class called Person which contains one data field called name and method whoami().

hashtag
What is self? #

All methods in python including some special methods like initializer have first parameter self. This parameter refers to the object which invokes the method. When you create new object the self parameter in the __init__ method is automatically set to reference the object you have just created.

hashtag
Creating object from class #

Expected Output:

note:

When you call a method you don't need to pass anything to self parameter, python automatically does that for you behind the scenes.

You can also change the name data field.

Expected Output:

Although it is a bad practice to give access to your data fields outside the class. We will discuss how to prevent this next.

hashtag
Hiding data fields #

To hide data fields you need to define private data fields. In python you can create private data field using two leading underscores. You can also define a private method using two leading underscores.

Let's see an example

Expected Output:

Let's try to access __balance data field outside of class.

Expected Output:

AttributeError: 'BankAccount' object has no attribute '__balance'

As you can see, now the __balance field is not accessible outside the class.

In next chapter we will learn about operator overloadingarrow-up-right.

Other Tutorials (Sponsors)

This site generously supported by DataCamparrow-up-right. DataCamp offers online interactive Python Tutorialsarrow-up-right for Data Science. Join over a million other learners and get started learning Python for data science today!

Sourcearrow-up-right

Homearrow-up-right
Blogarrow-up-right