Objects of a Class
Objects are instances of classes. They represent real-world entities or concepts and encapsulate data (attributes) and behavior (methods).
Creating Objects:
To create an object of a class, you use the class name followed by parentheses:
Python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
In this example, person1 and person2 are objects of the Person class.
Accessing Attributes and Methods:
You can access an object's attributes and methods using the dot notation:
Python
print(person1.name) # Output: Alice
person1.greet() # Calls the greet() method
Object Identity:
Each object has a unique identity, which is determined by its memory address. You can compare objects using the is operator to check if they refer to the same object:
Python
if person1 is person2:
print("Same object")
else:
print("Different objects")
Key Points:
- Objects are instances of classes.
- They encapsulate data and behavior.
- You can create multiple objects from the same class.
- Each object has its own unique attributes and methods.