Object
In Python, everything is an object. This includes not just instances of classes that you or others define, but also fundamental data types (like numbers, strings, and lists) and even functions and types themselves. Each object in Python has a type (which is itself an object), a unique identity (typically, its memory address), and a value (the data it holds).
Basics of an Object
An object encapsulates data and behavior. Data is stored in attributes, and behavior is defined by methods (functions associated with an object). The concept of an object in programming is closely related to real-world objects: just as a car has attributes (like color, make, model) and behaviors (like driving, braking), an object in Python has attributes and methods.
Creating and Using an Object
Objects are instances of classes. A class can be thought of as a blueprint for objects; it defines the attributes and methods that its instances (objects) will have.
Here’s an example revisiting the User class:
class User:
def __init__(self, name, email):
self.name = name
self.email = email
def display_info(self):
print(f"Name: {self.name}, Email: {self.email}")
To create an object of the User class:
user1 = User("Alice", "alice@example.com")
Here, user1 is an object of the User class, with name and email attributes. You can interact with the object using its methods:
user1.display_info()
This will output:
Name: Alice, Email: alice@example.com
Object Identity, Type, and Value
- Identity: Every object in Python has an identity, which can be thought of as the object’s address in memory. The id() function returns the identity of an object.
- Type: The type of an object determines what kind of object it is (e.g., str, list, User) and what operations it supports. You can get the type of an object using the type() function.
- Value: The value of an object is the data it holds. For immutable objects (like integers, floats, strings, and tuples), the value doesn't change. For mutable objects (like lists, dictionaries, and instances of most classes), the value can be changed.
Special Methods
Classes in Python can implement certain special (or magic) methods that are surrounded by double underscores (e.g., __init__, __str__, __len__). These methods provide a way for your classes to implement and interact with built-in behaviors or operators. For example, __str__ can be used to return a human-readable string representation of the object, which is handy for debugging and logging.
Python's object-oriented nature allows for encapsulation, inheritance, and polymorphism, making it powerful for organizing and reusing code.