In Python, an object is a collection of data (variables) and methods (functions) that operate on the data.
In Python, Everything is an object, including built-in data types, user-defined classes, functions, and modules.
Here are some key points about objects in Python:
# Create an object of a class obj_name = YourClassName(arguments)
In Python, everything is an object, including integers, floats, strings, lists, tuples, dictionaries, functions, classes, and modules.
This means that each object has a type (class) and can be manipulated and passed around like any other value.
We can create objects by instantiating classes.
A class is a blueprint for creating objects, and an object is an instance of a class.
To create an object, we call the class as if it were a function, which creates a new instance of the class.
class YourClass: pass obj = YourClass() # Creating an object of MyClass # Validating type of class object has print("Type of Class Object has: ", type(obj)) # Output: Type of Class Object has: <class '__main__.YourClass'>
Objects have attributes, which are variables associated with the object, and methods, which are functions associated with the object.
We can access attributes and methods using the dot notation ("object.attribute" or "object.method()").
class Employee: def __init__(self, name, deptName): self.name = name self.deptName = deptName def displayEmployeeDetail(self): print("Name: " + self.name + "\nDepartment: ", self.deptName) empObj = Employee("Alice", "HR") # Creating an object of Employee # Access Attributes and functions of class through object print(empObj.name) # Output: Alice print(empObj.displayEmployeeDetail()) # Output: Name: Alice Department: HR
Each object in Python has a unique identity, which is a memory address where the object is stored.
We can get the identity of an object using the "id()" function.
obj = MyClass() print(id(obj))
Every object in Python has a type, which is the class it belongs to.
We can get the type of an object using the "type()" function.
obj = "Hello" print(type(obj)) # Output: <class 'str'>
Objects can behave differently based on the methods they implement.
For example, different types of objects can support different operations (e.g., arithmetic operations for numbers, string operations for strings).
Python supports object-oriented programming (OOP) principles, such as encapsulation, inheritance, and polymorphism.
We can define our classes and create objects with custom behaviours and properties.
Objects are central to Python programming, and understanding how objects work is essential for effective Python development, especially when working with classes and modules in larger projects.