Objects are the cornerstone of Pythonβs object-oriented programming (OOP) paradigm. Everything in Python is an objectβintegers, strings, functions, modules, and even classes. Understanding how objects work is fundamental to mastering Python. Objects encapsulate data and behavior, allowing developers to build modular and maintainable applications. This document explores the concept of objects in Python in detail, covering creation, attributes, identity, methods, memory, and how Python treats everything as an object.
In Python, an object is a data structure that combines data (attributes) and behavior (methods). An object is an instance of a class, and every object in Python has the following characteristics:
x = 10
print(type(x)) # <class 'int'>
print(id(x)) # Memory ID (unique)
Python treats everything as an object, including functions, modules, and even classes. This means every value has a type and a unique identity.
print(isinstance(10, object)) # True
print(isinstance("Hello", object)) # True
print(isinstance(len, object)) # True
A class is a blueprint for creating objects. It defines the structure (attributes) and behavior (methods) that the object will have.
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
return f"{self.name} says woof!"
my_dog = Dog("Rex", "Labrador")
print(my_dog.bark()) # Rex says woof!
Attributes store the state of an object. They are defined using self.attribute inside the class.
print(my_dog.name) # Rex
print(my_dog.breed) # Labrador
Methods are functions defined within a class that operate on instances of that class.
print(my_dog.bark()) # Rex says woof!
Magic methods in Python start and end with double underscores. These are used to customize class behavior.
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __str__(self):
return f"{self.title}, {self.pages} pages"
b = Book("Python Basics", 300)
print(str(b)) # Python Basics, 300 pages
a = [1, 2, 3]
print(id(a)) # Identity (memory address)
print(type(a)) # <class 'list'>
print(isinstance(a, list))# True
Objects in Python are either:
my_list = [1, 2, 3]
my_list.append(4) # This modifies the list (mutable)
my_str = "hello"
# my_str[0] = "H" # TypeError (strings are immutable)
Encapsulation is the bundling of data and methods into a single unit (class) and restricting access to some components.
class Car:
def __init__(self, model):
self.__model = model # Private attribute
def get_model(self):
return self.__model
c = Car("Tesla")
print(c.get_model()) # Tesla
class Animal:
def speak(self):
return "Animal sound"
class Dog(Animal):
def speak(self):
return "Woof"
d = Dog()
print(d.speak()) # Woof
def animal_sound(animal):
print(animal.speak())
animal_sound(Dog()) # Woof
animal_sound(Animal()) # Animal sound
class Sample:
count = 0 # Class attribute
def __init__(self):
Sample.count += 1
s1 = Sample()
s2 = Sample()
print(Sample.count) # 2
s1.name = "Object 1"
print(s1.name) # Object 1
Python uses reference counting to track the number of references to an object.
import sys
a = [1, 2, 3]
print(sys.getrefcount(a)) # Number of references
Python automatically reclaims memory using the garbage collector for objects no longer in use.
import gc
gc.collect() # Trigger garbage collection manually
class MyObject:
pass
obj = MyObject()
obj.name = "Dynamic"
print(obj.name) # Dynamic
a = [1, 2]
b = [1, 2]
print(a == b) # True (same value)
print(a is b) # False (different objects)
def modify_list(lst):
lst.append(4)
nums = [1, 2, 3]
modify_list(nums)
print(nums) # [1, 2, 3, 4]
print(dir(list)) # Shows all attributes/methods of list
help(str) # Displays documentation for string class
print(hasattr(my_dog, 'bark')) # True
print(getattr(my_dog, 'name')) # Rex
setattr(my_dog, 'age', 5)
print(my_dog.age) # 5
class Dynamic:
def __getattr__(self, name):
return f"{name} not found"
obj = Dynamic()
print(obj.x) # x not found
class LifeCycle:
def __init__(self):
print("Object created")
def __del__(self):
print("Object deleted")
obj = LifeCycle()
del obj # Object deleted
Objects are used to represent real-world entities like students, accounts, books, etc.
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
In frameworks like Django or Flask, objects represent database records, HTTP requests, sessions, etc.
Libraries like Tkinter and PyQt use objects to define windows, buttons, labels, etc.
Understanding objects in Python is crucial for becoming proficient in the language. Everything in Python is built around the concept of objectsβwhether you are manipulating strings, building web applications, or performing data analysis. Grasping how objects are created, manipulated, and managed in memory allows developers to write cleaner, more maintainable, and efficient code.
By embracing object-oriented concepts like encapsulation, inheritance, and polymorphism, and leveraging dynamic features like introspection and runtime attribute creation, Python developers can build powerful and flexible applications.
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is βΉ5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from βΉ3,000 - βΉ1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved