PYTHON OBJECTS

Marco Niño
6 min readJan 15, 2020

--

Introduction

Python is an object-oriented programming language, that means, it’s composed of objects that interact with each other, with this we can create a lot of different elements using a bunch of “templates” and each one of those elements will be an interation of a “template” called “class”.

Say for example, we have a class named “Dog”:

We can have infinite doges!

The class must be named with a first capital letter, it deffines the attributes (like breed, size, age, etc.) of each instance of itself that is cretated, and also the methods (eat(), sleep(), etc.()) which are the actions (or functions) the instances of the class can do.

To create an instance in python use use:

class Dog: # Use a capital letter to start the name of the class    def __init__(self, name="", age=0, breed=""): #initialize the class
self.name = name
self.age = age
self.breed = breed

This will create a simple class called “Dog” we can use to create any dog we want.

Now to define what are the values the each dog can take, use go with the getters and setters.

@property
def name(self):
return self.__name # The "__" means it's a private attribute.
@name.setter
def name(self, value):
if type(name) != str: # To verify the name is a string
raise TypeError("Name of the dog must be a string.")
self.__name = value # Sets the new name for the dog.

The same thing must be done for each of the attributes of the class (remember the identation).

Now we defined what our dog is, but not what it can do; for that we define the actions it can do inside of the class:

def eat():
print("{}'s favorite food is meat".format(self.name))

In this brief example the action (method) the dog will do with eat() is inform us that the dog likes meat. You have to define each of the methods you want your dog to do, a puppy needs its training after all.

Id and Type

To create a new instance of the class Dog, we use it as such:

>>> schna = Dog("Gusanito", 5, "Schnauzer")#Class(name, age, breed)

And just like that, what took hundreds of thousands of years of biology and selective breeding, we did in a few microseconds.

Now, what happens when we try to print our new dog?

>>> print(schna)
<__main__.Dog object at 0x7f64f98f60b8> # The number may vary

That doesn’t look like a dog at all… it says that the the variable points to a Dog object at that specific memory position (in hex). To know who our dog is, we need to get its ID:

>>> print(id(schna))
140594955342008

The id is a Python Build-in function, it takes an object and returns an integer (long int) that is unique and constant for this object as long as it lives. But two objects may have the same id if they don’t exist at the same time.

id(object): Returns unique number assigned to an object.

Now we will ask the system about the type of our dog

>>> print(type(schna))
<class '__main__.Dog'>

It says that our dog has a type “Class” that belongs to the class “Dog”

Type will tell us what kind of variable is the argument we pass to it, this Build-in command is usefull when we want to compare if two objects are exactly the same type.

>>> print(type(schna) == type(labra))
True

We just checked that our dog (schna) is the same type of another dog (labra) created from the same class.

Mutable Objects and Inmutable Objects in Python

When a program grows in code and complexity, it’s sometimes necesary that some of the values change over time, some of the variable types can’t be changed after they’re defined, some others can be modified according to the current program needs; list are one of these “mutable” types.

These objects are used to embody values that vary over time, our dogs are the same dogs, even when their age change, maybe we got them a haircut, an accesory, etc. it’s the same dog. The same happens with objects, they can have changing values but that doesn’t change what they are.

>>> dog_list = ["Schnauzer", "Labradone", "Shiba Inu"]
>>> dogs_for_adoption = dog_list

We create a dog list and we make “dog_list_adoption” equal to dog_list, what this will do is first create a list of the dos, then asign the dog_list var to point to that list, then the dogs_for_adoption variable is set to point to the same list as dog_list; what this means is, if we do something like:

>>> print(dog_list)
["Schnauzer", "Labradone", "Shiba Inu"]
>>> dogs_for_adoption.remove("Shiba Inu") # Modify the second var
>>> print(dog_list)
["Schnauzer", "Labradone"]

That would mean that we modified the “dog_list” without calling it.

The dog got a new family

On the other hand there are objects in Python that cannont be modified when they are defined, cases like integers (int), floating point numbers (float), strings (str) or tuples (tuple) among others. For example:

>>> dog_name = "Monty"
>>> dog_name[1] = "a"
Traceback (most recent call last):
...
TypeError: 'str' object does not support item assignment

The same with tuples:

>>> dog_age_size = (4, 63) #Age in years, Size in cm
>>> dog_age_size[0] = 5
Traceback (most recent call last):
...
TypeError: 'tuple' object does not support item assignment

Although the objects themselves are inmutable, that doesn’t mean the elements in the object are too, lets see:

>>> dog_list_adoption = ("A new hope", ["Schnauzer", "Labradone", "Shiba Inu"])

In here we defined a tuple that contains the name of the shelter that houses the dogs for adoption and the breed of the dogs. As you can see there is a list inside of the tuple and as we saw earlier, lists are mutable, so:

>>> dog_list_adoption[1].remove("Shiba Inu") #Got adopted
>>> print(dog_list_adoption) #Check the list
('A new hope', ['Schnauzer', 'Labradone'])

We just mutated an element in an inmutable object.

Arguments in functions

As we all now, all programming languages use functions in them to define the behavior of the programs in an organized and standarized manner, but then comes the questions: How are arguments passed to functions? What are the implication for mutable and inmutable objects?

Well were here to answer that, first is important to know that memory management is greatly affected by the correct use of the proper object; lets take for example this function to create a copy of a list:

def copy_dog_list(dog_list):
copied_list = []
for i in dog_list:
copied_list.append(i)
return copied_list

As we saw earlier using “copied_list = dog_list” just creates another variable that points to the same original list; with this function we create a new variable that points to another list with the same elements as the original dog_list. Now, the argument passed to that function is a list, a mutable object, that means it can be changed inside the function, if you don’t want your variable to change you need to make a copy of it. For inmutable objects there is no need to do so, that’s because they can’t be changed anyway.

Let’s see another example:

def update_dog_list(dog_list, change=0): # Modifies a dog list
if change== 0: # Remove if change == 0
removed_dog = input("Input name of dog to remove: ")
dog_list.remove(removed_dog)
else: # Add if change == 1
added_dog = input("Input name of dog to add: ")
dog_list.append(added_dog)

This simple function will modify a list of dogs depending on the change (0~1) to be made. So we have:

>>> dog_list = ["Graham C.", "Jhon C.", "Terry G.", "Eric I."]
>>> print(id(dog_list))
139660537918024 # Your numbers may vary
>>> update_dog_list(dog_list, 0) # With 0 we remove
Input name of dog to remove: Jhon C.
['Graham C.', 'Terry G.', 'Eric I.']
139660537918024 # The same id

This is a call by reference so the changes are made to the original list.

Let’s see what happens in this case:

def dog_age_update(age):
print(age)
age = age + 1

This functions “updates” the age of a puppy by summing 1, let’s see if it works

>>> age = 3
>>> print(id(age))
10105152
>>> dog_age_update(age)
3
>>> print(age)
3
>>> print(id(age))
10105152

Well that didn’t do much… That’s because in this case, the function calls the variable by value, not by reference, and as such it only gets the value stored in the variable and not the reference to the variable itself. It’s a lot like pointers in C.

--

--