Exploring Variables in Python: A Deep Dive into Object-Oriented Concepts

O

Ohidur Rahman Bappy

MAR 22, 2025

Exploring Variables in Python: A Deep Dive into Object-Oriented Concepts

Overview of OOP Terminology

  • Class − A user-defined blueprint for creating objects that defines attributes and methods. Attributes are data members accessed via dot notation.

  • Class Variable − Shared by all instances of a class, defined within a class but outside any methods. Less frequently used than instance variables.

  • Data Member − A member variable (either class or instance) associated with a class and its objects.

  • Function Overloading − Assigning multiple behaviors to a function, based on object types or arguments.

  • Instance Variable − A variable defined inside a method, specific to the current instance of a class.

  • Inheritance − The mechanism of deriving new classes from existing ones, inheriting attributes and behaviors.

  • Instance − An individual object of a certain class.

  • Instantiation − The process of creating an instance of a class.

  • Method − Special functions defined within a class.

  • Object − A unique instance containing data members and methods, defined by a class.

  • Operator Overloading − Assigning different methods to a particular operator.

Define a Class

class Dog:
    # Class attribute
    species = "Canis familiaris"

    # Constructor
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # Destructor
    def __del__(self):
        class_name = self.__class__.__name__
        print(class_name, "destroyed")

    def __new__(cls):
        print("__new__ magic method is called")
        inst = object.__new__(cls)
        return inst

    # Instance method
    def description(self):
        return f"{self.name} is {self.age} years old"

    def setWeight(self, weight):
        self.__weight = weight

    def getWeight(self):
        return self.__weight

    def setColor(self, color):
        self._color = color

    def speak(self, sound):
        return f"{self.name} says {sound}"

    def __cmp__(self, other):
        return True if self.name == other.name else False

    def __add__(self, other):
        return self.age + other.age

    def __str__(self):
        return f"{self.name} is {self.age} years old"

    def __repr__(self):
        return f"{self.name} is {self.age} years old"
>>> miles = Dog("Miles", 4)
>>> print(miles)
'Miles is 4 years old'

Child Class

class BullDog(Dog):
    # Method overriding
    def speak(self, sound="Arf"):
        return f"{self.name} says {sound}"

Use issubclass() or isinstance() to check relationships between classes and instances.

>>> jack = Bulldog("Jack", 3)

>>> isinstance(miles, BullDog)
False

>>> isinstance(jack, Dog)
False
class Employee:
   empCount = 0

   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1

   def displayCount(self):
     print("Total Employee %d" % Employee.empCount)

   def displayEmployee(self):
      print("Name : ", self.name,  ", Salary: ", self.salary)

emp1 = Employee("Zara", 2000)
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print("Total Employee %d" % Employee.empCount)
print(id(emp1))

Output:

Name :  Zara ,Salary:  2000
Name :  Manni ,Salary:  5000
Total Employee 2
3782888

Attributes can be added, modified, or deleted anytime.

Instead of normal statements, use:

  • getattr(obj, name[, default])
  • hasattr(obj, name)
  • setattr(obj, name, value)
  • delattr(obj, name)

Built-In Class Attributes

Accessed using dot operator like any other attribute:

  • dict − Class namespace dictionary.

  • doc − Class documentation string.

  • name − Class name.

  • module − Module name where class is defined.

  • bases − Base classes tuple.

Deleting an object:

del emp1

classmethod() in Python

class Person:
    name = "Ohidur"

    def print_name(obj):
        print("The name is : ", obj.name)

Person.print_name = classmethod(Person.print_name)
Person.print_name()

The @classmethod and @staticmethod Decorator

from datetime import date 

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

    @classmethod
    def fromBirthYear(cls, name, year):
        return cls(name, date.today().year - year)

    @staticmethod
    def isAdult(age):
        return age > 18

person1 = Person('mayank', 21)
person2 = Person.fromBirthYear('mayank', 1996)

print (person1.age)
print (person2.age)

print (Person.isAdult(22))

Output:

21
22
True

Python property() Function

class Alphabet:
    def __init__(self, value):
        self._value = value

    def getValue(self):
        print('Getting value')
        return self._value

    def setValue(self, value):
        print('Setting value to ' + value)
        self._value = value

    def delValue(self):
        print('Deleting value')
        del self._value

    value = property(getValue, setValue, delValue)

x = Alphabet('GeeksforGeeks')
print(x.value)
x.value = 'GfG'
del x.value

Output:

Getting value
GeeksforGeeks
Setting value to GfG
Deleting value

Using @property Decorator

class Alphabet:
    def __init__(self, value):
        self._value = value

    @property
    def value(self):
        print('Getting value')
        return self._value

    @value.setter
    def value(self, value):
        print('Setting value to ' + value)
        self._value = value

    @value.deleter
    def value(self):
        print('Deleting value')
        del self._value

x = Alphabet('Peter')
print(x.value)
x.value = 'Diesel'
del x.value

Python Data Class

dataclasses module simplifies the creation of data classes, which means less boilerplate.

from dataclasses import dataclass

@dataclass(unsafe_hash=True)
class InventoryItem:
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def total_cost(self) -> float:
        return self.unit_price * self.quantity_on_hand

This module also supports comparison methods and handling of immutability.