1. Home
  2. Docs
  3. Object Oriented Programming in Python
  4. Classes, Objects,Attributes, Methods

Classes, Objects,Attributes, Methods

 

Object Oriented Python

 

This section is brief over view of Object Oriented Python.

Here we will explore building blocks of OOP.

Python is a pure Object Oriented Programming language.

Everything in Python is an object.

That means even numbers, strings, functions, modules, classes etc are all objects.

Programming languages like C,C++, Java have primitive data types, which are not objects.

 

What is an object ?

 

An object is a unit of data of a class or type.

Object have one or more attributes and functionality.

Attributes of an objects are also called properties,

and functionality are implemented in methods.

If any of the above lines making no sense, don’t worry,

You will get there, when we look at the, concrete examples of objects.

For the moment, understand objects in Python are no different than, real life objects,

like , Car, Person, Laptop, House, Office, etc.

 

What every object has ?

 
Every object has,

  1. a Type
  2. an Id
  3. Attribute(s), some of them are Method(s)
  4. Value(s), of attributes.

 

If you have done at least a bit of Python programming,

then you have already used objects, without knowing them.

Let’s explore some built-in objects in Python and try to understand.

 

Example:
  

my_int = 10 # my_int variable referring to 10

# check type of object my_int referring to

print(type(my_int)) 

# get id of the object my_int referring to

print(id(my_int)) 

  
Here my_int  is a variable, which is pointing to place in memory which holds value 10.

We can check what type of object my_int is referring to by using built-in function type()

Also each object has a unique ID, that can be checked by another built-in function id(),

In CPython implementation id is nothing but memory address of the object.

 

Output:

<class 'int'>

1488478656

 
 
“my_int” is referencing an object of class int, int is short hand for integer.

it has value 10,

its id is 1488478656

and other properties of my_int can be obtained by another built-in function dir()

dir(obj) built in function lists the properties of a given object.
 
 

dir(my_int)

 

Check yourself these, by typing above code in Python interpreter.

The below table has few other built-in objects.

For simplicity, only type and Id are shown.

Like above check,  type and id of these objects in Python interpreter.

 

ObjectTypeId
my_int = 10class 'int'1488478656
my_string = "Welcome"class 'str'1488772652424
my_list = ['Apple', 'Orange','Grapes']class 'list'1488772571848
my_bool = Trueclass 'bool'1487986848
my_tuple = cclass 'tuple'1488772335560
my_dict ={"name" :"User"}class 'dict'
1488772640704
my_type = type(type(10))class 'type'

1488040944

 
Please note even “type” is an object,
  

my_type = type(type(10))

print(type(my_type))

print(id(my_type))

dir(my_type)

  
which is of class ‘type’ with a unique id.
  

type => <class 'type'>

id => 1488040944

  

Until now, we discussed about objects which are built-in Python.

Let’s look at, how to create user defined class or types.

 

Classes

  
The user defined objects are created by using the ‘class’ keyword.

The ‘class’ is like a blueprint,

that defines the nature of a future object.

By using classes we construct instances.

In Python we have two types of syntax for class creation,

1. Old or classic style

2. New style

Below you will see examples for both styles,

but for the rest of the course, we will fallow New style syntax.

Syntax:

Old Style:
  

class ClassName():

      statements

or 

Parentheses are not mandatory after class name.
class ClassName:

      statements

  
New style:
 

class ClassName(BaseClasses):

      statements

 
 

Now lets create a new user defined object type called MyClass,
  

class MyClass(object):

    pass  #pass is keyword, equals to do nothing

  
By convention class names starts with a capital letter.

 

In the above example MyClass is class name,

the class statement binds the classname and class body.

Currently the class body, we don’t have anything. So MyClass is of no use.

A class can have arbitrary named attributes.
 

Body of a class

 
Body of a class where you normally specify the attributes of a class.

 

Attributes

 

Inside MyClass, we currently just have pass

Which means, this class don’t have any implementation, and is useless.

Let’s add some implementation by adding attributes.

An attribute is a characteristic of an object.

Attributes can be divided into states and behaviors.

Functions can be an attributes of a class, these are called methods.

Behaviors are implemented by using methods,

and states are defined using variables .

The terms attributes and  properties are interchangeable.

 

Method

 
Methods, are functions which are defined inside a class.

An operation, we can perform with the object are implemented as methods..

Method is also know as “callable attribute” of the class.

Let’s get a better understanding of attributes through an example.

The syntax for adding an attribute  to class is:
  

class MyClass(object):

    x = 10

  

x is an attribute of a class, which is defined,
 
inside class body and it refers value 10.

We can access the attribute of a class by using dot notation.

 

Dot notation

 
A Python attribute can be accessed by using ( . ) dot notation as below.

The ( . ) dot notation can be used to set and get the attributes.

Dot is used after the class name or object name fallowed by attribute name.
  

MyClass.x

  
we can print and check what is x holding.

print(MyClass.x)

output:

10

  
In the above example we have defined attributes inside class body.

But in Python attributes can also be added dynamically,

outside the class body, by using dot notation.
  

MyClass.y = 20


print(MyClass.y)

output:

20

  

There is no difference between defining attributes inside or outside of class body.
 

Function as attribute

 
We can also define inside as class, which is called as method.

Lets define a say_hello() method inside MyClass.
  

class MyClass(object):
    x = 10
    
    def say_hello():
        print("Hello, There!")

 
As function is also an attribute, we call it by using dot notation.
  

MyClass.say_hello()

output:

Hello, There!

  
When we use class statement, Python implicitly adds some useful attributes to class,

like __name__ and __bases__

We can check these on our MyClass class.
  

print(MyClass.__name__)

print(MyClass.__bases__)


output:

MyClass

(<class 'object'>,)

  
Notice __name__ returns name of the class,

and bases returns the inherited class name.

You will learn more about inheritance in later section.

class also has another useful attribute called __dict__

the dict object holds other attributes of the class.
  

print(MyClass.__dict__)


{'__dict__': <attribute '__dict__' of 'MyClass' objects>,
              '__doc__': None,
              '__module__': '__main__',
              '__weakref__': <attribute '__weakref__' of 'MyClass' objects>,
              'say_hello': <function __main__.MyClass.say_hello>,
              'x': 10,
              'y': 20}


  

Private attributes.

 
An identifier starting with two underscores inside a class, is private member.
  

like __num_elements = 10

  
We cannot access private members directly by using a dot notation.

See in the below example, x is not a private member,

__num_elements is private member. only x can be accessed with dot notation.
  

class Myclass(object):
    x = 10
    __num_elements = 10
    
    
print(MyClass.x)

output:


print(MyClass.__num_elements)

output:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-31-f6eb2d6af7d8> in <module>()
      7 
      8 
----> 9 print(MyClass.__num_elements)
     10 
     11 

AttributeError: type object 'MyClass' has no attribute '__num_elements'


  

But private attributes can be accessed by using methods.
 

Creating Instance from user defined class

 
To create an instance, use class as if it is function.
  


obj_1 = MyClass()

obj_2 = MyClass()

  

# creates an object, returns its reference

obj_1 = MyClass()

# Address of the first object

print("Address of first object :", obj_1)

output:

Address of first object : <__main__.MyClass object at 0x0000026F6DD9DB00>

  
Crating your second object.
  

obj_2 = MyClass()

# Address of the second object

print("Address of second object :",obj_2)


Output:

Address of second object : <__main__.MyClass object at 0x0000026F6DDA85C0>

 
 

In above example MyClass(),
 
each time constructs an object and returns a reference to that object.

obj_1 points to an object at  0x0000026F6DD9DB00 in memory location.

obj_2 points to an object at  0x0000026F6DDA85C0 in memory location.

 

 

Module Vs Class

We will explore more about attributes in the next lesson,

But before that lets understand the difference between classes and modules.

Let’s understand.

 

What is the difference between modules and classes ?

 

Python modules are files containing Python code.

Modules can be executed individually, or imported in some other module and get executed.

A module may contain, classes, properties or functions any of these or all of these.

 

Where as a class is Python code inside a module.
 

Let’s look at an example of accessing a class from a module.

 

Example:
  

from decimal import Decimal

# Decimal is a class name starts with 'D'
num1 = Decimal('1.5') 

num2 = Decimal('2.5')

print(num1 + num2)

 

Output:

4.0

Here Decimal is class inside decimal module,

which is part of standard Python installation.

in the above example, Decimal class is imported from decimal module.

 

In the next section we will look at some more examples of class and objects.