Python Classes
Categories:
2 minute read
The __init__()
method in Python is a special method within a class that is automatically called when a new object is created, allowing for initialization and setup of instance variables.
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.")
# Creating instances of the Person class
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
# Accessing attributes
print(person1.name) # Output: Alice
print(person2.age) # Output: 30
# Calling methods
person1.greet() # Output: Hello, my name is Alice and I'm 25 years old.
person2.greet() # Output: Hello, my name is Bob and I'm 30 years old.
In this example, we have a class called Person
that represents a person. The class has an __init__
method, which is called when an object is created from the class. It initializes the attributes name
and age
using the values passed as arguments.
The class also has a method called greet
, which prints a greeting message using the name
and age
attributes of the object.
We then create two instances of the Person
class, person1
and person2
, passing different values for the name
and age
parameters.
We can access the attributes of an object using dot notation. For example, person1.name
gives us the name attribute of person1
.
To call a method on an object, we use dot notation as well. For example, person1.greet()
calls the greet
method of person1
, which prints a greeting message.
When running this code, it will output:
Alice
30
Hello, my name is Alice and I'm 25 years old.
Hello, my name is Bob and I'm 30 years old.