In Python, objects and classes are fundamental concepts of object-oriented programming (OOP). Object-oriented programming allows you to create objects with their own attributes and methods, making code organization clear and maintainable.
Defining a Class in Python
- To define a new class, use the
class
keyword, followed by the name of the class (usually starting with an uppercase letter). - Inside the class, you can define attributes (variables) and methods (functions) that objects of the class will have.
Creating Objects from a Class
- To create an object from a class, use the syntax
class_name()
. - This will initialize a new object based on the defined class.
Example: Here's a simple example of how to define a class and create objects from it:
# Define the class Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# Create objects (instances) from the class Person
person1 = Person("John", 30)
person2 = Person("Alice", 25)
# Call the say_hello method from the objects
person1.say_hello() # Output: Hello, my name is John and I am 30 years old.
person2.say_hello() # Output: Hello, my name is Alice and I am 25 years old.
In the example above, we defined the Person
class with two attributes name
and age
, along with a method say_hello()
. Then, we created two objects person1
and person2
from the Person
class and called the say_hello()
method of each object to display their information.