Improve your Python Programming: All about Classes and Objects(Part 1)

Venkata_Kiran
4 min readSep 12, 2022

The class is a fundamental building block in Python. Understanding what classes are, when to use them, and how they can be useful is essential, and the goal of this article.

Source: Google Images
Source: Google Images

In Python, everything is an object and for example let’s see the below code:

print(type(1))
print(type([]))
print(type(()))
print(type({}))
Output:<class 'int'>
<class 'list'>
<class 'tuple'>
<class 'dict'>

So we know all these things are objects, so how can we create our own Object types? That is where the class keyword comes in.

The class is a blueprint that defines the nature of a future object. From classes we can construct instances. An instance is a specific object created from a particular class.

Let see how we can use class:

class Customer(object):
"""A customer of ABC Bank with a checking account. Customers have the following properties:

Attributes:
name: A string representing the customer's name.
balance: A float tracking the current balance of the customer's account.
"""

def __init__(self, name, balance=0.0):
"""Return a Customer object whose name is *name* and starting balance is *balance*."""
self.name = name
self.balance = balance
def withdraw(self, amount):
"""Return the balance remaining after withdrawing *amount*
dollars."""
if amount > self.balance:
raise RuntimeError('Amount greater than available balance.')
self.balance -= amount
return self.balance

def deposit(self, amount):
"""Return the balance remaining after depositing *amount*
dollars."""
self.balance += amount
return self.balance

The class Customer(object) line does not create a new customer. That is, just because we've defined a Customer doesn't mean we've created one; we've merely outlined the blueprint to create a Customer object. To do so, we call the class's __init__ method with the proper number of arguments (minus self, which we'll get to in a moment).

So, to use the “blueprint” that we created by defining the class Customer (which is used to create Customer objects), we call the class name almost as if it were a function: Venkat = Customer('Venkata', 1000.0). This line simply says "use the Customer blueprint to create me a new object, which I'll refer to as Venkat."

The venkat object, known as an instance, is the realized version of the Customer class. Before we called Customer(), no Customer object existed. We can, of course, create as many Customer objects as we'd like. There is still, however, only one Customer class, regardless of how many instances of the class we create.

self?

So what’s with that self parameter to all of the Customer methods? What is it? Why, it's the instance, of course! Put another way, a method like withdraw defines the instructions for withdrawing money from some abstract customer's account. Calling venkat.withdraw(100.0) puts those instructions to use on the venkat instance.

So when we say def withdraw(self, amount):, we're saying, "here's how you withdraw money from a Customer object (which we'll call self) and a dollar figure (which we'll call amount). self is the instance of the Customer that withdraw is being called on. That's not me making analogies, either. venkat.withdraw(100.0) is just shorthand for Customer.withdraw(venkat, 100.0), which is perfectly valid (if not often seen) code.

__init__

self may make sense for other methods, but what about __init__? When we call __init__, we're in the process of creating an object, so how can there already be a self? Python allows us to extend the self pattern to when objects are constructed as well, even though it doesn't exactly fit. Just imagine that venkat = Customer('Venkat', 1000.0) is the same as calling venkat = Customer(venkat, 'Venkat', 1000.0); the venkat that's passed in is also made the result.

This is why when we call __init__, we initialize objects by saying things like self.name = name. Remember, since self is the instance, this is equivalent to saying venkat.name = name, which is the same as venkat.name = 'venkat'. Similarly, self.balance = balance is the same as venkat.balance = 1000.0. After these two lines, we consider the Customer object "initialized" and ready for use.

Instance Attributes and Methods

A function defined in a class is called a “method”. Methods have access to all the data contained on the instance of the object; they can access and modify anything previously set on self. Because they use self, they require an instance of the class in order to be used. For this reason, they're often referred to as "instance methods".

Let’s go through an example of creating a Circle class:

class Circle:
pi = 3.14

# Circle gets instantiated with a radius (default is 1)
def __init__(self, radius=1):
self.radius = radius
self.area = radius * radius * Circle.pi

# Method for resetting Radius
def setRadius(self, new_radius):
self.radius = new_radius
self.area = new_radius * new_radius * self.pi

# Method for getting Circumference
def getCircumference(self):
return self.radius * self.pi * 2


c = Circle()

print('Radius is: ',c.radius)
print('Area is: ',c.area)
print('Circumference is: ',c.getCircumference())
output:Radius is: 1
Area is: 3.14
Circumference is: 6.28

In the __init__ method above, in order to calculate the area attribute, we had to call Circle.pi. This is because the object does not yet have its own .pi attribute, so we call the Class Object Attribute pi instead.
In the setRadius method, however, we’ll be working with an existing Circle object that does have its own pi attribute. Here we can use either Circle.pi or self.pi.

Now let’s change the radius and see how that affects our Circle object:

c.setRadius(2)

print('Radius is: ',c.radius)
print('Area is: ',c.area)
print('Circumference is: ',c.getCircumference())
output:Radius is: 2
Area is: 12.56
Circumference is: 12.56

Notice how we used self. notation to reference attributes of the class within the method calls.

For now, this is all about classes and objects and I’ll see in Part2…

Link to Part 2:

https://medium.com/@ktirupati82/improve-your-python-programming-all-about-classes-and-objects-part-2-602e5b05a047

Sources:

https://www.udemy.com/course/complete-python-bootcamp/learn/lecture/9478312#overview

https://jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/

--

--

Venkata_Kiran

Data Analytics professional, Seasonal fitness freak, explorer...