Classes and Objects in Python

Mannan Ul Haq
0

Object-Oriented Programming in Python:

Object-Oriented Programming (OOP) is a paradigm that organizes data into distinct units called objects, which contain both data (Variables/Properties) and the methods (Functions) to operate on that data. OOP helps in modeling real-world entities, promoting code reuse, and establishing relationships between different entities.


OOP uses concepts like:

  • Encapsulation: It means bundling data and methods that operate on that data within a single unit, i.e., class.
  • Abstraction: It hides the complex reality while exposing only the necessary parts.
  • Inheritance: It allows a class to inherit the properties and methods of another class.
  • Polymorphism: Allows one interface to be used for a general class of actions.


Classes:

A class is a blueprint for creating objects. Classes encapsulate data for the object and methods to manipulate that data.


To create a class, use the keyword `class`:


class ClassName :
    <properties>
    <methods>


For example:


class Dog :
    breed = ""  # property

    def bark(self) : # method
        print("Woof!")



Objects:

An object is an instance of a class. It's a self-contained unit that consists of both data (properties) and procedures to manipulate the data (methods).


To create an object of a class:


objectName = ClassName()


Using the above `Dog` class:


my_dog = Dog()
my_dog.breed = "Golden Retriever"
my_dog.bark()  # Output: Woof!


We can access the class variables and methods using the dot operator (.).



Properties and Methods:

Properties:

Properties are the characteristics of an object. These are the variables defined within a class. In the above example, `breed` is an attribute of the `Dog` class.


These variables can be classified into two main categories: instance variables and class variables.


1. Instance Variables: 

These are the variables that are defined inside a method and belong only to the current instance of the class. They are often initialized in the `__init__` method, which is the constructor method in Python classes. Each instance of the class has its own copy of the instance variable, meaning changes made to the variable don't reflect in other instances of the class.


class MyClass :
    def __init__(self, value) :
        self.instance_variable = value


In this example, `instance_variable` is an instance variable.


2. Class Variables:

These are variables that are shared across all instances of the class. They are defined outside of any method, usually just below the class header. Since they are shared, changes made to this variable will be reflected in all instances of the class.


class MyClass :
    class_variable = "I am a class variable"

    def __init__(self, value) :
        self.instance_variable = value


In this example, `class_variable` is a class variable.


Types of Properties:

In Python, classes can have different types of properties (or variables) based on their accessibility. The primary ones are public and private.

1. Public Properties:

By default, all attributes and methods defined in a class in Python are public. This means they can be accessed both from within the class and from instances of the class (objects), as well as outside the class.

class SampleClass :
    def __init__(self) :
        self.public_property = "I am public!"

obj = SampleClass()
print(obj.public_property)  # Output : I am public!

2. Private Properties:

Python doesn't have strict private member access like some other languages, but it does offer a mechanism to indicate that a property or method is intended to be private, which is by prefixing the name with double underscores `__`. These attributes are not directly accessible from outside the class.

class SampleClass :
    def __init__(self) :
        self.__private_property = "I am private!"

obj = SampleClass()
# print(obj.__private_property)  # This will raise an error.

Methods:

Methods are functions defined within a class that describe the behaviors of the objects. The `bark()` in the `Dog` class is a method.


Classification:

Class methods are classified as:
  • Getter Functions: Used to get the value of private properties.
  • Setter Functions: Used to set the value of private properties.
  • Utility Functions: General functions to perform operations.

class Circle :
    def __init__(self, radius) :
        self.__radius = radius  # private property

    # Getter
    def get_radius(self) :
        return self.__radius

    # Setter
    def set_radius(self, value) :
        self.__radius = value

    # Utility Function
    def area(self) :
        return 3.14 * self.__radius * self.__radius


Initializing Properties (Constructor):

The `__init__()` method, commonly known as the constructor in Python's object-oriented programming. 

`__init__()` Method:

The `__init__()` method is a special method automatically called when an object of a class is instantiated. It's used for initializing the attributes of a class. 

1. Default Initializer:

When you do not provide any `__init__()` method in your class definition, Python provides a default one with no arguments.

class SampleClass :
    variable = " "

obj = SampleClass()

2. Parameterized Initializer:

You can provide arguments to the `__init__()` method to initialize object properties when the object is created.

class SampleClass :
    def __init__(self, value) :
       self.my_property = value

obj = SampleClass("Hello")
print(obj.my_property)  # Output : Hello

3. Initializer with Default Values:

Python allows function arguments to have default values. This applies to the `__init__()` method as well. This means you can instantiate objects even if you do not provide values for all the arguments, as the default values will be used.

class SampleClass :
    def __init__(self, value = "Default Value") :
        self.my_property = value

obj1 = SampleClass("Hello")
print(obj1.my_property)  # Output : Hello

obj2 = SampleClass()
print(obj2.my_property)  # Output : Default Value

The `self` Parameter:

The `self` parameter is a reference to the current instance of the class and is used to access variables and methods associated with that instance. 

In Python, `self` is explicitly passed as the first parameter to instance methods, including the `__init__()` method. However, when you call a method, you don't provide a value for `self`, Python does it for you. 

To further illustrate:

class SampleClass :
    def __init__(self, value) :
        self.my_property = value  # 'self' refers to the object being created

    def display(self) :
        print(self.my_property)

obj = SampleClass("Hello")
obj.display()  # No need to pass a value for 'self'

The term "self" is a convention. You could technically use another name, but it's strongly recommended to stick with `self` for clarity and consistency with other Python code.


Deleting Properties and Objects (Destructor):

Deleting object properties and objects is a crucial aspect of memory management in object-oriented programming. In Python, you can delete properties from an object and even delete the object itself. Furthermore, Python offers a mechanism, the destructor, to handle object destruction.

1. Delete Object Properties:

In Python, you can use the `del` keyword to delete properties from an object.

class SampleClass :
    def __init__(self, value) :
        self.my_property = value

obj = SampleClass("Hello")
print(obj.my_property)  # Output : Hello

del obj.my_property
# print(obj.my_property)  # This will raise an error as 'my_property' no longer exists.

2. Delete Objects:

You can also use the `del` keyword to delete objects. This operation removes the reference to the object, making it eligible for garbage collection.

obj = SampleClass("Hello")
del obj

# obj.display()  # This will raise an error as 'obj' no longer exists.

3. Destructor (`__del__` method):

The destructor is a special method, `__del__()`, that is invoked when an object is about to be destroyed. It's often used to release external resources used by the object, like closing files, releasing memory, or disconnecting network connections.

However, in Python, the destructor isn't as crucial as in some other languages due to the presence of the garbage collector, which handles memory management automatically.

Here's a simple example of using the destructor:

class SampleClass :
    def __init__(self, value) :
        self.my_property = value

    def display(self) :
        print(self.my_property)

    # Destructor
    def __del__(self) :
        print(self.my_property + " object is being destroyed")

obj1 = SampleClass("Hello")
obj2 = SampleClass("World")

del obj1  # Output: Hello object is being destroyed
del obj2  # Output : World object is being destroyed

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !