In Python, a class is a blueprint for creating objects that define properties and methods. An object is an instance of a class, which can have its own unique values for the class properties and can call its methods.
Here is an example of creating a class and an object in Python:
python # Define a class class Person: def __init__(self, name, age): self.name = name self.age = age def introduce(self): print("Hello, my name is " + self.name + " and I am " + str(self.age) + " years old.") # Create an object of the class person1 = Person("Alice", 30) # Call a method of the object person1.introduce() # Output: "Hello, my name is Alice and I am 30 years old."
In this example, a class called `Person` is defined with two properties (`name` and `age`) and one method (`introduce()`) that outputs a message to the console. The `__init__()` method is a special method that is called when an object is created and sets the initial values of the properties. The `self` parameter refers to the object that is being created.
An object of the `Person` class is created with the `Person(“Alice”, 30)` statement. The `introduce()` method of the object is then called with the `person1.introduce()` statement, which outputs a message to the console.
Classes in Python can also have inheritance, which means that a subclass can inherit the properties and methods of a parent class. Here is an example:
python # Define a parent class class Person: def __init__(self, name, age): self.name = name self.age = age def introduce(self): print("Hello, my name is " + self.name + " and I am " + str(self.age) + " years old.") # Define a child class that inherits from the parent class class Student(Person): def __init__(self, name, age, school): super().__init__(name, age) self.school = school def study(self): print("I am studying at " + self.school) # Create an object of the child class student1 = Student("Bob", 25, "University") # Call a method of the object student1.introduce() # Output: "Hello, my name is Bob and I am 25 years old." student1.study() # Output: "I am studying at University"
In this example, a parent class called `Person` is defined with two properties (`name` and `age`) and one method (`introduce()`). A child class called `Student` is defined that inherits from the `Person` class and adds one property (`school`) and one method (`study()`).
An object of the `Student` class is created with the `Student(“Bob”, 25, “University”)` statement. The `introduce()` and `study()` methods of the object are then called with the `student1.introduce()` and `student1.study()` statements, which output messages to the console.
Classes and objects are a powerful feature of Python and are used extensively in object-oriented programming.