Python From Beginner to Advanced

0% completed

Previous
Next
Python - Object and Classes

In the Object-Oriented Programming (OOP), classes and objects are fundamental concepts that facilitate the creation of structured, modular, and maintainable code. Understanding how to effectively utilize classes and objects is essential for any Python developer aiming to build scalable and robust applications.

What are Classes and Objects?

Image
  • Classes: A class in Python acts as a blueprint for creating objects. It encapsulates data for the object and methods to manipulate that data. A class defines attributes and the behavior of its objects, as if it were sketching out the characteristics and capabilities of those objects.

  • Objects: An object is an instance of a class. When a class is defined, no memory is allocated until an object of that class is created. Objects are instances that are constructed following the structure of their class template and can have data and behavior as defined by the class.

Defining Classes

Defining a class in Python starts with the class keyword followed by the class name and a colon. Inside the class, methods and attributes are defined to specify the capabilities and data of the objects.

Image

Example

In this example, we will define a simple class Dog with some basic methods.

Python3
Python3

. . . .

Explanation:

  • class Dog: declares a new class named Dog.
  • speak(self): An instance method that allows the dog to "speak", or rather, return a string of what the dog would say.
  • Creating a Dog object named my_dog demonstrates how to instantiate objects of the class Dog.

Class Attributes

Class attributes are variables defined directly in the class that are shared by all instances of the class. They can be useful for storing constants and default values that should be the same for every instance.

Example

In this example, we will define a class attribute in the Dog class that identifies the species.

Python3
Python3

. . . .

Explanation:

  • species = "Canine": A class attribute that is shared among all instances of the Dog class, defining all dogs as belonging to the "Canine" species.
  • print(Dog.species): Demonstrates accessing a class attribute using the class name itself rather than an instance, highlighting that this attribute is shared across all instances.

Class Constructor

In Python, the class constructor is the method that is automatically invoked when a new object is created. It is defined using the __init__ method. This method is crucial as it allows for the initialization of attributes in new objects.

Example

In this example, we will cover the constructor of the Dog class to initialize its attributes.

Python3
Python3

. . . .

Explanation:

  • class Dog:: Defines a class called Dog.
  • def __init__(self, name, age): The constructor method that sets up the name and age when a new Dog object is created.
  • self.name = name and self.age = age: Assign the values passed to the constructor to the name and age attributes of the object.
  • puppy = Dog("Rex", 2): Creates a new instance of Dog named puppy.
  • The print statement confirms that the attributes have been initialized correctly.

Built-In Class Attributes

Python provides several built-in attributes for classes that provide information about the class structure. These include __dict__, __doc__, __name__, __module__, and __bases__, which can be used for introspection and are very useful in more advanced Python applications.

Example

In this example, we will explore some built-in attributes of the Dog class.

Python3
Python3

. . . .

Explanation:

  • Dog.__doc__: Accesses the class's documentation string, which is a brief description of the class.
  • Dog.__name__: Retrieves the name of the class.
  • Dog.__module__: Displays the name of the module in which the class was defined.

Class Methods

Class methods are methods that are bound to the class rather than its object. They can modify the class state that applies across all instances of the class, rather than individual object instances. To define a class method in Python, you use the @classmethod decorator.

Example

In this example, we will implement a class method in the Dog class to keep track of the total number of dogs.

Python3
Python3

. . . .

Explanation:

  • total_dogs = 0: A class attribute that keeps a count of how many Dog instances have been created.
  • Dog.total_dogs += 1: Increments the total_dogs counter each time a new Dog instance is initialized.
  • @classmethod: Decorator that specifies get_total_dogs as a class method.
  • def get_total_dogs(cls): Defines a class method that returns the total_dogs count. It uses cls to refer to the class.
  • The print statement outputs the total number of Dog instances, demonstrating how class methods can be used to access class-wide data.

Static Methods

Static methods are used when functionality is related to a class but does not need to access any class-specific data nor its instance data. Static methods are defined with the @staticmethod decorator and do not receive an implicit first argument (neither self nor cls).

Example

In this example, we will define a static method in the Dog class that provides a general utility unrelated to the specific attributes of any instance.

Python3
Python3

. . . .

Explanation:

  • @staticmethod: Indicates that is_dog_friendly is a static method.
  • def is_dog_friendly(): A method that returns True, indicating dogs are friendly. It does not interact with class or instance data.
  • The print statement uses the class name to access the static method, illustrating that static methods can be accessed either through the class or its instances but operate independently of both.

Destroying Objects (Garbage Collection)

In Python, objects are automatically destroyed when they are no longer needed. Python's garbage collector runs during program execution and deallocates objects that are no longer referenced, which frees up memory.

Example

In this example, we'll discuss how Python handles object destruction.

Python3
Python3

. . . .

Explanation:

  • __init__(self, name): Initializes new Dog objects with a name and prints a message.
  • __del__(self): This is the destructor method. It gets called when an object is about to be destroyed and prints a message indicating this.
  • del my_dog: Explicitly deletes the my_dog instance.
  • gc.collect(): Forces garbage collection to reclaim unreferenced objects. This line is usually unnecessary but can be used to demonstrate or ensure that garbage collection has occurred.

The examples provided explore the various aspects of class-related functionalities in Python, emphasizing how different types of methods and automatic garbage collection support efficient and clear object-oriented programming. These concepts are pivotal for creating well-structured OOP applications in Python.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next