Introduction to Classes
Contents
Introduction to Classes¶
Today we will discuss how to define our own classes and objects in Python.
Classes and Methods¶
Python supports many different kinds of data:
1234 (int), 3.14 (float), “Hello” (str) [1, 5, 7, 11, 13] (list), {“CA”: “California”, “MA”: “Massachusetts”} (dict)
Each of these is an object, and every object has:
a type
an internal data representation (primitive or composite)
a set of methods for interaction with the object
Classes allow us to define our own objects and data types in Python. After defining a class, we can create an instance of a class and interact with that instance using methods.
All methods belong to a specific class, and are defined within that class. A method’s purpose is to provide a way to access/manipulate objects (or specific instances of the class).
The first parameter in the method definition is the reference to the calling instance (self
). When invoking methods, this reference is provided implicitly.
Simple Class and Method¶
Let’s define a simple class with a single method that prints “Hello” and see how we can call the method on an instance of the class.
class SampleClass:
"""Class to test the use of methods"""
def greeting(self):
print("Hello")
sample = SampleClass()
sample.greeting()
Hello
Digging Deeper: Self¶
Lets try to understand what the purpose of the parameter self
by using the python function id()
.
Recall that id(obj)
displays the unique identifier to the object. You can think of this number as the address in memory this object is stored.
Let us rewrite class SampleClass
to print the id
of self.
class SampleClass:
"""Class to test the use of methods"""
def greeting(self):
print("Hello, object with ID", id(self))
obj = SampleClass()
obj.greeting()
Hello, object with ID 4425923792
id(obj)
4425923792
In addition to methods, classes define important features of objects through attributes. Every instance of a class has different attribute values! In Python, we declare attributes using __slots__
. __slots__
is a list of strings that stores the names of all attributes in our class (note that only names of attributes are stored, not the values!) __slots__
is typically defined at the top of our class (before method definitions).
class SampleClass:
"""Class to test the use of methods"""
__slots__ = ["name"]
# give values to attributes in __init__
# more on this next time!
def __init__(self, n):
self.name = n
def greeting(self):
print("Hello, object with ID", id(self))
def getName(self):
print(self.name)