You are on page 1of 12

Objects are real world entities.

Anything you can describe in this world is


an object. Classes on the other hand are not real. They are just a concept.
Class is a short form of Classification. A class is a classification of certain
objects and it is just a description of the properties and behavior all objects
of that classification should possess.

Class is a like a recipe and the object is like the cupcake we bake using it.
All cupcakes created from a recipe share similar characteristics like shape,
sweetness, etc. But they are all unique as well. One cupcake may have
strawberry frosting while another might have vanilla. Similarly, objects of
a class share similar characteristics but they differ in their values for those
characteristics.

What does a recipe contain? It contains list of ingredients which make up


the cake and the directions. Similarly, a class contains the
properties/attributes of the object and the operations/behavior that can be
performed on an object.

ou would classify the below object as a Mobile:

This is because the object has price and brand and we have defined that all
objects which have a price and brand are considered to belong to the Mobile
classification. This object cannot be classified as a shoe because it does not
have a material property.
Thus we can say that this object is an example of or instance of the Mobile
classification. Under this classification, there can be many objects and the
object shown above is an instance of or example of it.

A class is defined using the class keyword in python. For example, the
below code creates a class called Mobile without any attributes or behavior.

class Mobile:
pass

Like any programming language, python also has built-in classes. Some of
the built-in classes which you have already used are:

 List
 Date
 Tuple
 Set

 To create an object, we need a class. The syntax for creating an


object is "<classname>()", where <classname> is the name of the
class.

 For example, the below code creates three Mobile objects:


 Mobile()
 Mobile()
 Mobile()

We already discussed that List is an inbuilt class. But did you ever create a
list object using List()?

Object literal is a special syntax through with objects are created and
initialized.
For e.g. for list this syntax is square bracket followed by any number of
values of objects separated by comma followed by closing bracket. So the
expression you see on right side of assignment operator is the object literal
for list. Object literal for different objects are different to distinguish from
each other.

For example,

 list1 = [1,2,3]
 dict1 = {"name": "Gopal", "age": 32}
 tup1 = (1,2,3)

Only some inbuilt objects can be created using object literals.

Just like we need variables to access and use values, we need variables to
access and reuse the objects that we create. Such variables that are used
to access objects are called reference variables .
In the below code, we are creating three objects, each with its own
reference variable

mob1=Mobile()
mob2=Mobile()
mob3=Mobile()
Python

Copy

We will discuss more in detail about reference variable later.


If two objects look the same and have the same values, can we treat it as
Single object?

How can we create attributes and values for those attributes? This can be
done by using the . (dot) operator. The syntax for creating attribute and
value for that is as below:

reference_variable.attribute_name=value.
For example, in the below code we are creating two attributes price and
brand, and assigning them to the two objects we had created.

class Mobile:
pass

mob1=Mobile()
mob2=Mobile()

mob1.price=20000
mob1.brand="Apple"

mob2.price=3000
mob2.brand="Samsung"

In python, we can create attributes for a specific object alone. In the below
example, the mob1 object has an ios version which mob2 does not have.

mob1.price=20000
mob1.brand="Apple"
mob1.ios_version=10

mob2.price=3000
mob2.brand="Samsung"

We can update the value of an existing attribute using the dot operator.
For example, the below code will change the ios_version of mob1 object,
since the mob1 object already has that attribute.
mob1.ios_version=11
Python

Copy

In python, if we assign a value to a non-existent attribute, it will create that


attribute for that object alone. For example, the below code will create an
attribute for mob2 object alone.

mob2.android_version="Marshmallow"

If we try to access a non-existing attribute, we will get an Attribute Error.


For example,

print (mob2.ios_version)

The rules for a class attribute are very similar to a variable. You just have
to treat reference_variable.attribute_name as a variable.

Variable Attribute

Variable_name = reference_variable.attribute_name = value


value creates the creates the attribute and assigns the value if the
variable and assigns attribute does not exist already.
the value if the
variable does not For example:
exist already.
m1.color = "Green"
For example:

x=5

Variable_name = reference_variable.attribute_name = value


value updates the the updates the attribute if the attribute exists
value if the variable already.
exists already.
Variable Attribute

For example:
For example:
m1.color = "Green"
x=5
m1.color = "Red"
x=6

Accessing a non- Accessing a non-existent attribute throws an


existent variable error
throws an error
A variable can be The value of an attribute can be assigned to
assigned to another another variable.
variable.
For example:
For example: c1 = m1.color
y=x

When we create an object, the special __init__() function inside the class of that object is invoked
automatically. This special function is called as a constructor. Try out the below code and observe
the output.

class Mobile:
def __init__(self, brand, price):
print("Inside constructor")
self.brand = brand
self.price = price

mob1=Mobile("Apple", 20000)
print("Mobile 1 has brand", mob1.brand, "and price", mob1.price)

mob2=Mobile("Samsung",3000)
print("Mobile 2 has brand", mob2.brand, "and price", mob2.price)
Python
Copy

Note: self has a special meaning which we will discuss soon. Also, attributes are created
using self.attribute_name.

You can also create a constructor without parameters. But this is rarely useful.

Also note that even though the constructor has a parameter self, we don't explicitly have to
pass value for that parameter. This will be discussed more in detail later. If a constructor
takes parameters and if we invoke it with a different number of parameters, the error message
will indicate how many parameters were missed out or exceeded.
class Mobile:
def __init__(self,one,two):
print("Inside constructor")

#mob1=Mobile()
#mob1=Mobile(100,200,300)

We can create behavior in a class by adding functions in a class. However, such functions
should have a special parameter called self as the first parameter. We will discuss more about
the syntax later on. This is how the purchase behavior in a mobile class would look like:

class Mobile:
def __init__(self):
print("Inside constructor")

def purchase (self):


print("Purchasing a mobile")

mob1=Mobile()
mob1.purchase()
Python
Copy

Such functions which describe the behavior are also called as methods. We can invoke the
methods using the dot operator as shown:

Even though purchase() is accepting a parameter called self, we need not pass it when we
invoke it. We will see why later.

We can access an attribute in a method by using self. Value of the attribute accessed inside
the method is determined by the object used to invoke the method. For example, in the code
below when we invoke purchase using mob1, attribute values (Apple and 20000) of mob1 are
accessed. Similarly, when mob2 is used to invoke purchase, attribute values (Samsung and
3000) of mob2 are accessed in purchase().

class Mobile:
def __init__(self, brand, price):
print("Inside constructor")
self.brand = brand
self.price = price

def purchase(self):
print("Purchasing a mobile")
print("This mobile has brand", self.brand, "and price", self.price)

print("Mobile-1")
mob1=Mobile("Apple", 20000)
mob1.purchase()

print("Mobile-2")
mob2=Mobile("Samsung",3000)
mob2.purchase()
Python
Copy
We will see how this is happening later when we discuss more about self.

In python, everything is an object. Thus everything would have either attributes or behavior
or both. That means even numbers, strings, list, set, dictionary, etc are all treated as objects in
python. For example,

Example Description
Here we are invoking a method
is_integer() on a numerical value.
(12.5).is_integer()
That means numerical values are
all objects
Here we are invoking upper()
"hello".upper()
method on a string object.
Here we are invoking the reverse
[1,2,3].reverse()
method on a list object

Function Method
Is a block of code with a Is part of an object and represents
name the behavior of the object
It can be invoked using the Can be invoked only on an object,
name of the function and using dot operator. Without an
passing parameters object we cannot invoke a method

Example: len([1,2,3]) Example: [1,2,3].reverse()


A method must have at least one
Parameters are optional in a
parameter : self
function

Unlike the complex engineering diagrams, a class diagram is quite simple. It has four parts:
the name of the class, the list of attributes, the list of methods and access specifiers.

Note: We will discuss more about access specifiers later

 Reference variables hold the objects


 An object can have multiple reference variables
 Assigning a new reference variable to an existing object does not create a new object
 We can create objects without reference variable as well
 Class diagrams represent the class with its attributes and behaviour

LOCK
class Customer:
def __init__(self, cust_id, name, age, wallet_balance):
self.cust_id = cust_id
self.name = name
self.age = age
self.wallet_balance = wallet_balance

def update_balance(self,amount):
if amount < 1000 and amount > 0:
self.wallet_balance += amount

def show_balance(self):
print("The balance is ",self.wallet_balance)

c1=Customer(100, "Gopal", 24, 1000)


c1.update_balance(500)
c1.show_balance()

But with the way currently it is coded, the data can be accidentally changed by directly
assigning a incorrect value to it as shown below:

class Customer:
def __init__(self, cust_id, name, age, wallet_balance):
self.cust_id = cust_id
self.name = name
self.age = age
self.wallet_balance = wallet_balance

def update_balance(self, amount):


if amount < 1000 and amount > 0:
self.wallet_balance += amount

def show_balance(self):
print ("The balance is ",self.wallet_balance)

c1=Customer(100, "Gopal", 24, 1000)


c1.wallet_balance = 10000000000

c1.show_balance()

We can put a lock on that data by adding a double underscore in front of it, as shown below:

class Customer:
def __init__(self, cust_id, name, age, wallet_balance):
self.cust_id = cust_id
self.name = name
self.age = age
self.__wallet_balance = wallet_balance

def update_balance(self, amount):


if amount < 1000 and amount > 0:
self.__wallet_balance += amount
def show_balance(self):
print ("The balance is ",self.__wallet_balance)

c1=Customer(100, "Gopal", 24, 1000)


print(c1.__wallet_balance)
Python
Copy

Adding a double underscore makes the attribute a private attribute. Private attributes are those
which are accessible only inside the class. This method of restricting access to our data is
called encapsulation

To have a error free way of accessing and updating private variables, we create specific methods for
this. Those methods which are meant to set a value to a private variable are called setter methods
and methods meant to access private variable values are called getter methods. The below code is
an example of getter and setter methods:
class Customer:
def __init__(self, id, name, age, wallet_balance):
self.id = id
self.name = name
self.age = age
self.__wallet_balance = wallet_balance

def set_wallet_balance(self, amount):


if amount < 1000 and amount> 0:
self.__wallet_balance = amount

def get_wallet_balance(self):
return self.__wallet_balance

c1=Customer(100, "Gopal", 24, 1000)


c1.set_wallet_balance(120)
print(c1.get_wallet_balance())

All setter methods must accept the value to be updated as a parameter and all getter methods
must not have any parameter and they must return the value.

Setter methods are called as mutator methods ( as they change or mutate the value ) and the
getter methods are called accessor methods ( as they access the values )

class Customer:
def __init__(self, id, name, age, wallet_balance):
self.id = id
self.name = name
self.age = age
self.__wallet_balance = wallet_balance

def set_wallet_balance(self, amount):


if amount < 1000 and amount> 0:
self.__wallet_balance = amount

def get_wallet_balance(self):
return self.__wallet_balance
c1=Customer(100, "Gopal", 24, 1000)
c1.set_wallet_balance(120)
print(c1.get_wallet_balance())

PRACTICE QUESTION
A university wants to automate their admission process. Students are admitted based on

marks scored in a qualifying exam.

A student is identified by student id, age and marks in qualifying exam. Data are valid, if:

 Age is greater than 20


 Marks is between 0 and 100 (both inclusive)

A student qualifies for admission, if

 Age and marks are valid and


 Marks is 65 or more

Write a python program to represent the students seeking admission in the university.

Continuing with the previous scenario, a student eligible for admission has to choose a course
and pay the fees for it. If they have scored more than 85 marks in qualifying exam, they get
25% discount on fees.

Valid course ids and fees are given below:

course id fees
1001 25575.0
1002 15500.0

Extend the program written in the previous assignment to include the above requirement.

You might also like