Instantiating Python Classes
After understanding the basic concept of Python classes, the next step is to learn how to create instances of a class, which are called objects.
Creating Objects
To create an object (instance) of a class, you use the class name followed by a pair of parentheses ()
. This process is called instantiation. Here's an example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I'm {self.age} years old.")
## Create two instances of the Person class
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
In the above example, we create two instances of the Person
class: person1
and person2
. Each instance has its own set of attributes (name
and age
) and can access the greet()
method.
Accessing Object Attributes
You can access the attributes of an object using the dot notation (object.attribute
). For example:
print(person1.name) ## Output: Alice
print(person2.age) ## Output: 25
You can also modify the attributes of an object using the same dot notation:
person1.age = 31
print(person1.age) ## Output: 31
Calling Object Methods
To call a method of an object, you use the dot notation (object.method()
). For example:
person1.greet() ## Output: Hello, my name is Alice and I'm 31 years old.
person2.greet() ## Output: Hello, my name is Bob and I'm 25 years old.
By understanding how to create instances of a Python class and access their attributes, you can start building more complex and powerful applications using the principles of object-oriented programming.