Python Object Basics
Understanding Python Objects
In Python, everything is an object. An object is a fundamental concept that encapsulates data and behavior. Each object has three main characteristics:
- Identity
- Type
- Value
graph TD
A[Python Object] --> B[Identity]
A --> C[Type]
A --> D[Value]
Object Creation and Initialization
Python allows object creation through various methods:
Class Instantiation
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
## Creating an object
john = Person("John Doe", 30)
Built-in Object Types
Python provides several built-in object types:
Type |
Description |
Example |
int |
Integer numbers |
x = 10 |
float |
Floating-point numbers |
y = 3.14 |
str |
String |
name = "LabEx" |
list |
Mutable sequence |
items = [1, 2, 3] |
dict |
Key-value pairs |
data = {"key": "value"} |
Object Attributes and Methods
Every object in Python has attributes and methods:
class Car:
def __init__(self, brand, model):
self.brand = brand ## Attribute
self.model = model ## Attribute
def start_engine(self): ## Method
print(f"{self.brand} engine started")
Object References
Python uses references to manage objects:
a = [1, 2, 3]
b = a ## Both a and b reference the same list
b.append(4) ## Modifies the original list
print(a) ## Output: [1, 2, 3, 4]
Memory Management
Python uses automatic memory management through:
- Reference counting
- Garbage collection
Best Practices
- Use meaningful object names
- Follow Python naming conventions
- Keep objects simple and focused
- Use type hints for clarity
By understanding these basics, you'll build a strong foundation for working with Python objects in your programming journey with LabEx.