OOP fundamentals

Constructors, methods, and attributes are fundamental concepts in object-oriented programming that help you define and work with classes and objects.

Attributes are the data members of a class. They represent the characteristics or properties of objects created from that class. Attributes store data that describes the state of the object. Attributes can be variables of various data types.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person1 = Person("Alice", 30)
print(person1.name)  # Output: "Alice"
print(person1.age)   # Output: 30

In this example, "name" and "age" are attributes of the "Person" class.

A constructor is a special method that is automatically called when an object is created from a class. It initializes the object's attributes with the values provided during object creation. In Python, the constructor is named "__init__".

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person1 = Person("Alice", 30)
person2 = Person("Bob", 25)

Methods are functions defined within a class. They perform actions or operations related to the class. Methods can access and manipulate the attributes of the object they belong to.

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 am {self.age} years old.")

person1 = Person("Alice", 30)
person1.greet()  # Output: "Hello, my name is Alice and I am 30 years old."

In this example, "greet()"" is a method of the "Person" class that prints a personalized greeting.

Attributes, constructors, and methods work together to define the behavior and structure of classes and objects in object-oriented programming. Attributes store data, the constructor initializes the object, and methods provide functionality that can be performed on the object's data. This combination allows you to create well-structured and organized code for solving complex problems.