Instant Search

Everything is Object in Python

There are many confusions about what really is object in programming language or python. I promise you will get solid knowledge of objects after reading this post. I will try to explain in brief with real life examples that what really object is in python.

Lets divide this section in some parts :

  • Object
  • Objects by reference
  • Everything is object in python
  • Assignment operator in python
  • Immutable and mutable
  • What is mutable default argument
  • Variables are object references variables are not values

 

Object , Variable and Value

So first before going to talk about object in python let’s talk about some real life things. You know we all have a name like my Internet name is “exe” your name can be “Tim” or anything ok. We all know we have body and we also know there is something called “Soul” which live inside body and causes of soul we are alive. (Its something spiritual but you will get good idea bout object by this reference ) so basically what our parents do is they provide a name to us and that name is a reference for calling  our body. Means if someone want to call my body he will simply call “Tim” . So we choose name for our body.

we can give many names to our body like a person can have many names , nick name can be difference , college name can be different , professional name can be different , His children call him by another name , His wife call him by another name etc. So our body is container which hold the name for the inner soul. If we change many names it will not effect soul but if we change our body means if we died then all names related to our body and body related to would everything will be finish,

Now pay attention we are here talking about three things :

Object
Value
Variable

Our soul is value.
Our Body is object , Inside object value are stored. It means inside body soul are lives.
Our name is variable , So “Tim” , “Exe” all are variable.

So i am trying to make you understand A variable is just a reference for object. Variable is not value. In real life Name are just for reference for our body , Name are not soul. We can change name like we can take girl name (Who cares?) , we can take animal name ? , We can take boy name whatever but my soul would be same and body will just accept a new name.

So If we change variable for a value it means we are changing name we are not changing value which are stored in object.

So, what’s a variable? As the name implies, a variable is something which can change. A variable is a way of referring to a memory location used by a computer program. In many programming languages a variable is a symbolic name for this physical location. This memory location contains values, like numbers, text or more complicated types. We can use this variable to tell the computer to save some data in this location or to retrieve some data from this location.

A variable can be seen as a container to store certain values.

 

 

Here X and Y are variable , Box are object which are holding 42 and 78 values.

In c language you have to define which type of data and type is in first line of program like:

But in Python we don’t have to panic about this , We don’t have to worry about data types and declaration , Just pick up any variable and use it with any data type.

Not only the value of a variable may change during program execution but the type as well. You can assign an integer value to a variable, use it as an integer for a while and then assign a string to the same variable.
the equal “=” sign in the assignment shouldn’t be seen as “is equal to”. It should be “read” or interpreted as “is set to”, meaning in our example “the variable i is set to 42”.

Now lets understand by example :

here i is variable which is holding value of 42 but actually i is not holding value 42 in reality i is referencing a object which is holding the value 42.

Here object is holding a int type value and i is referencing a int type value.

if you want to know to know type of value you know know by typing “type()”

You can see its int type.

Now i is referencing a object which is holding string type data. We are changing data type with same variable .

Now object is holding float value and i is referring that object.

So now lets come back on our point , As i said our body can have many names ok , Like my internet name is “exe” , My college name is “Ankit” , My friends call me “Paul” but i am one person means i have only one body and one soul but i have many names.

Same object is one but it can be have many names but value will be store in object not in variable in Python.

So:

exe is referring a object which is holding int data type value 1337 now :

Now pay attention we have set exe to 1337 now tim to exe.

Hi11

As you can see exe is referring value 1337 and tim is also referring value 1337 it means tim and exe are only names for object , exe and tim are not holding values they are just name .

We can check both are set to same data value by “id()” . The identity function id() can be used for this purpose. Every instance (object or variable) has an identity, i.e. an integer which is unique within the script or program, i.e. other objects have different identities.

you can see tim and exe have same id it means they are set to same data.

Now lets do something more :

guess the output: off course they both have same data value:

Hi11

 

So now i think you have very good idea about object , variable and value.

In integer type there are three operator where people most confuse :

/ , // and %

/ is Division
// Floor division
% is modular operator

In python 3 “/” operate integer by integer result in float number , Means it perform “True” division it gives result in float numbers :

where if we want only integer value not float value (like if you expect i am dividing integer by integer then i want integer result) then you should use // floor division :

Now what about modular operator :

Modular operator gives reminder in division :

Now lets talk about object reference and remember this thing you will need this thing in future when you will learn call by object :

Objects  reference

As i said variable are just name pointing to the object so it means variable are not holding values . Variables in Python aren’t values, they’re object references. When you call a Python function the arguments are copies of the references to the original object. Variable are just refereeing the object. That’s why variable are object reference.

Everything is an object in python:

What exactly it means Everything is an object in python

It means everything in Python is an object. Strings are objects. Lists are objects. Functions are objects. Even modules are objects.
everything is an object in the sense that it can be assigned to a variable or passed as an argument to a function.
Anything you can (legally) place on the right hand side of the equals sign is (or creates) an object in Python.

Let’s clear this concept so you can tell anybody what it really means.

so let’s define a small function.

and now when we run this program we get this output:

Wait wait what ?

What is this ??

So you were expecting some values but its printing function reference.
Now remember what i said above i said variable are just name for object reference so here “hi” is just a variable which is referencing the function “hello” and that’s why its printing the address of function.

The portion of the right hand side of the equals sign creates an object. Anything you can (legally) place on the right hand side of the equals sign is (or creates) an object in Python.

 

so when we assign “hi=hello” then hello is object there.

Here, a questions arises: How do we know that the thing on the right hand side of the equals sign will always be an object we can bind a name to?

let’s understand this:

if i write :

now as i said “The portion of the right hand side of the equals sign creates an object. Anything you can (legally) place on the right hand side of the equals sign is (or creates) an object in Python.”  so according to this now 1337 have to be an object . 1337 is just a value or object let’s check:

we will check this by “dir” method :

The purpose of the dir() function is to find out what names are defined in a given namespace, and return a list of those names. If called without arguments, it returns a list of the names defined in the local namespace. This function can be very handy for finding out what items are in a module or class.

in other words : dir() shows the all the attributes which 1337 have now lets check:

Its shows all the attributes which 1337  have now if 1337 were only just a value then it would not have these attributes. so 1337 is also object. Now for proof let’s pick up any attribute from that list and print with as instance of that variable .

first understand what print(exe.__add__) means:

When Python tries to evaluate x + y, it first attempts to call x.__add__(y). If this fails then it falls back to y.__radd__(x). In short, __add__() defines the behavior of + operator.

For example, 1 + 2 results in 3, whereas [3] + [4] results in [3, 4].

__add__ implements addition (+) operator.

We have tested on function that everything is object  now lets check on list :

As i have told you easiest method if you have to check that portion of the right hand side of the equals sign creates an object or not then just check by dir () method. it will list all the method associated with that object. and if it have methods and attributes then it means it is object.

exe=[1,2,3]

now [1,2,3] should have attributes if its object not only list.

perfect now pick up any attribute and again check with variable name:

As you can see its shows the address of list object.

So now i think you get it that “Everything is an object in python” and The portion of the right hand side of the equals sign creates an object. Anything you can (legally) place on the right hand side of the equals sign is (or creates) an object in Python.

Assignment:

 

So now assignment “=” are means the equal “=” sign in the assignment shouldn’t be seen as “is equal to”. It should be “read” or interpreted as “is set to”.

If we do exe=1 and then exe=”ankit” and then exe=1337.1 then it means we are just changing the namespace we are not changing the object.

I will explain in brief what is namespace , global and local variable and scope , Legb rule and many other things so for now just understand assignment change the namespace not the object.

like if we have exe=1 and then if we do exe=”ankit” it means that 1 is not effect by “ankit” and 1 doesn’t care at all.

 

 

So far what we have learned about about ?

#Objects

All Python objects have this:

  • a unique identity (an integer, returned by id(x))
  • a type (returned by type(x))
  • some content

You cannot change the identity.

You cannot change the type.

Some objects allow you to change their content. (Mutable Objects )

Some objects don’t allow you to change their content.(Immutable Objects)

Mutable and Immutable Objects:

Python have two types of objects :

  • Mutable objects.
  • Immutable Objects

 

Common immutable type:

  1. numbers: int(), float(), complex()
  2. immutable sequences: str(), tuple(), frozenset(), bytes()

Common mutable type (almost everything else):

  1. mutable sequences: list(), bytearray()
  2. set type: set()
  3. mapping type: dict()
  4. classes, class instances
  5. etc.

One trick to quickly test if a type is mutable or not, is to use id() built-in function.

Examples, using on integer,

using on list,

You have to understand that Python represents all its data as objects. Some of these objects like lists and dictionaries are mutable, meaning you can change their content without changing their identity. Other objects like integers, floats, strings and tuples … are objects that can not be changed. either you assign new value to object but they can’t be change. An easy way to understand that is if you have a look at an objects ID.

 

A mutable object has to have at least a method able to mutate the object. For example, the listobject has the append method, which will actually mutate the object:

but the class float has no method to mutate a float object. You can do:

but the = operand is not a method. It just make a bind between the variable and whatever is to the right of it, nothing else. It never changes or creates objects. It is a declaration of what the variable will point to, since now on.

When you do b = b + 0.1 the = operand binds the variable to a new float, wich is created with te result of 5 + 0.1.

When you assign a variable to an existent object, mutable or not, the = operand binds the variable to that object. And nothing more happens

In either case, the = just make the bind. It doesn’t change or create objects.

When you do a = 1.0, the = operand is not wich create the float, but the 1.0 part of the line. Actually when you write 1.0 it is a shorthand for float(1.0) a constructor call returning a float object. (That is the reason why if you type 1.0 and press enter you get the “echo” 1.0 printed below; that is the return value of the constructor function you called)

Now, if b is a float and you assign a = b, both variables are pointing to the same object, but actually the variables can’t comunicate betweem themselves, because the object is inmutable, and if you do b += 1, now b point to a new object, and a is still pointing to the oldone and cannot know what b is pointing to.

but if c is, let’s say, a list, and you assign a = c, now a and c can “comunicate”, because list is mutable, and if you do c.append('msg'), then just checking a you get the message.

(By the way, every object has an unique id number asociated to, wich you can get with id(x). So you can check if an object is the same or not checking if its unique id has changed.)

Assignments to immutable objects in python can be thought of as deep copies, whereas assignments to mutable objects are shallow.

 

 

 

So if we change one of them, like incrementing the value six by one, is it still a six? Well of course not. Thus any integer is immutable.

So: If any change in a virtual object means that it actually becomes another virtual object, then it is called immutable.

In Python, there’s a easy way to know:

Immutable:

Mutable:

And:

Now lets do something to understand more about mutable and immutable:

First understand on int (which is immutable ):

first a is 2 then when we change something in a a=a+1 then its not pointing the same value now its pointing the different value and its different object now. it means immutable can’t be change if we want to change we have to point them new object but they can’t be change with same id.what happened above you can understand by this image :

When we assign b=2 it takes old value of a ,

Now lets talk about mutable object (which is list):

output is

You can see now matter whatever we modify in mutable object but their id would be same as in above example first when we pass the argument x its id is 4338124744 when we modify the mutable object list and then print its id its still same and when we print again after function its id is still same.

Now here is some side effect too. as you can see when we pass list in function and then modify the list after when we return to old list then old is modify permanently. We can prevent this by passing copy of list instead of original list.

You can see now i am passing copy of list by [:] which will create a shallow copy of list and all the modification will effect the shallow copy not the original one.

its output is :

As you can see original list id is different and modify and passing list id are different. when we passed the list as argument it create a copy of list and that why original list id is different  , all the modification are effecting the copy of list that why passed and modify list id are same.

let’s understand this by one more example:

output :

Here ham and egg are just variable and they are pointing the same list that’s why ham and eggs id are same but when we assign egg=[2,3] then we assigned new object or new list to variable egg now egg is pointing new object but ham is still pointing old object or list.

Mutable default argument:

 

There is some gotcha in python , one is mutable default argument.

Lets say if you run this program:

output is :

 

Quite unexpected ? Yes it is

Now talk about python famous mutant default argument.
actually A new list is created each time the function is called if a second argument isn’t provided.

first when we pass f(1) it loop only 1 time with “0” iteration value.
second when we pass f(2) it loop 2 times with “0” and “1” iteration value but it will also add old value only if second argument is not provided.
same as til f(4) it will also add previous value of list and print will new value.
but when we pass second argument then its all methods fail and it simply print what is provided as argument like we passed f(4) with second argument [1,2] now it will not copy old value because list is not empty now it have some value which we provide in second argument. it will simply iterate 4 times and 0,1,2,3 with provide list value.

why its not adding old value now when we provide second argument ? because in second argument we passed a list so it this list which we provided will add in empty list now list is not empty that why it will not add old function values and it will simply work.

to prevent this mutant default argument we have to just use this method:

A new list is created once when the function is defined, and the same list is used in each successive call.

Python’s default arguments are evaluated once when the function is defined, not each time the function is called (like it is in say, Ruby). This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well.

What You Should Do Instead

Create a new object each time the function is called, by using a default arg to signal that no argument was provided (None is often a good choice).

Now you should have very solid knowledge about mutable and immutable objects in python.

At last always remember

Variables are object references variables are not values.

Now time for some cookies if you want more deep knowledge , i already tried to explain with brief explanation but if you still want checkout these cookies:

Cookies

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *