Delving into classes and objects in python

what are classes and why do we need them?

Classes provide a means of grouping data and functionality together in a program. but it’s not strictly necessary to have classes in python, as it supports functions, but since python was designed keeping OOP(object-oriented programming) in mind, we encounter classes. A class is like a blueprint for an object.

Class definition syntax :

class ClassName:
# Statement-1
.
.
.
# Statement-N

we use the word class followed by a user-defined name for the class while defining it and a semicolon.

#defining a class called Animals.
class Animals:
pass

Class Objects

An Object is an instance of a Class. what that essentially means is, In object-oriented programming (OOP), an instance is a concrete occurrence of any object, existing usually during the runtime of a computer program.

An object represents:

  • State: It is represented by the attributes of an object.
  • Behavior: It is represented by the methods of an object.
  • Identity: It gives a unique name to an object and enables one object to interact with other objects.
image by Daksh-Deepak\medium

Creating an object — also called instantiation

class Animals:
a1 = "cat"
a2 = "dog"
#A sample fucntion in the class
def func(self):
print("This is a ", self.a1)
print("This ia a", self.a2)#Object instantiationobj = Animals()#Accessing class attributes and method through objects
print(obj.a1)
obj.func()

You can access the elements of the class with the object using the dot operator.

The — init — () function

All classes have a function called __init__(), which is always executed when the class is being initiated.it’s used to assign values to object properties and variables. for example :

class Student:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Student("Aditi", 20)
print(p1.name)
print(p1.age)
Output:
Aditi
20

The Pass parameter

Class definitions cannot be empty, but if you for some reason have a class definition with no content put in the pass statement to avoid getting an error. as shown earlier.

The self parameter

The self parameter refers to the current instance of the class and is used to access variables that belong to the class. here's an example:

class Person:
def __init__(myobject, name, age):
myobject.name = name
myobject.age = age

def myfunc(abc):
print("Hello my name is " + abc.name)

p1 = Person("Amy", 40)
p1.myfunc()

Closure

A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory. Even when a function is invoked and is out of scope, a closure allows the function to access those captured variables through the closure’s copies of their values or references.

#Python program to illustrate closuresdef outerFunction(text)
text = text
def innerFunction():
print(text)
#we are returning functions without parenthesis
return innerFunction
if __name__ == '__main__':
myFunction = outerFunction('hello!')
myFunction()

Note:

The function innerFunction has its scope only inside the outerFunction. But with the use of closures, we can easily extend its scope to invoke a function outside its scope.

Decorators

Functions in Python are first-class citizens. A decorator is a design pattern in Python that allows a user to add new functionality to an existing object while maintaining its structure intact. Decorators are usually called before the definition of a function you want to decorate.

@ABC_decorator
def hello_decorator():
print("ABC")

'''Above code is equivalent to -

def hello_decorator():
print("ABC")

In the above code, ABC_decorator is a callable function, will add some code on the top of another callable function, hello_decorator function, and return the wrapper function.

pic by TechBeamers

Descriptors and Properties

Descriptors are Python objects that implement a method of the descriptor protocol, hence giving you the ability to create objects that have special behavior when they’re accessed as attributes of other objects.

Defining a definition protocol :

_get__(self, obj, type=None) -> object
__set__(self, obj, value) -> None
__delete__(self, obj) -> None
__set_name__(self, owner, name)

If your descriptor implements just -get — , then it’s said to be a non-data descriptor. If it implements .__set__() or .__delete__(), then it’s said to be a data descriptor.

The property() function is used to define properties in the Python class. The property() method in Python provides an interface to instance attributes. It encapsulates instance attributes and provides property.

we’ll explore more about properties in the upcoming posts!

A curious learner , an engineer by profession , exploring the world through writings