Object-oriented programming in Python
Object-oriented programming (OOP) is a programming paradigm that uses objects to represent data and the operations that can be performed on that data. Here's an example of creating a simple class in Python:
python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print("Hello, my name is", self.name)
In this example, we define a class called Person. The __init__ method is used to initialize the object with the name and age attributes. We also define a say_hello method, which prints a greeting message that includes the person's name.
To create a new Person object, we can simply call the class and pass in the required arguments:
python
p1 = Person("Alice", 30)
p2 = Person("Bob", 25)
p1.say_hello() # prints "Hello, my name is Alice"
p2.say_hello() # prints "Hello, my name is Bob"
In this example, we create two Person objects: p1 and p2. We then call the say_hello method on each object to print a greeting message.
No comments:
Post a Comment