Python is an object-oriented programming language that supports the creation of classes and objects. Classes are a blueprint for creating objects, while objects are instances of a class. In this tutorial, we will go through the basics of Python classes and objects with detailed code examples.
Creating a Class:To create a class in Python, we use the "class" keyword followed by the name of the class. Here's an example of a class that represents a car:
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def get_description(self):
return f"{self.year} {self.make} {self.model}"
In this example, we define a class named "Car" with three attributes: make, model, and year. We also define a constructor method "init()" which is called when an object of the class is created. The constructor takes three parameters: make, model, and year, and initializes the attributes of the class with these values.We also define a method named "get_description()" which returns a string containing the year, make, and model of the car.
Creating an Object:
To create an object of a class, we call the class like a function with any necessary arguments. Here's an example of creating an object of the "Car" class:
my_car = Car("Toyota", "Camry", 2022)
In this example, we create an object of the "Car" class and pass in the values "Toyota", "Camry", and 2022 for the make, model, and year attributes, respectively.
Accessing Object Attributes and Methods:
Once we have created an object of a class, we can access its attributes and methods using the dot notation. Here's an example of accessing the attributes and method of the "my_car" object:
print(my_car.make) # Output: Toyota
print(my_car.model) # Output: Camry
print(my_car.year) # Output: 2022
print(my_car.get_description()) # Output: 2022 Toyota Camry
In this example, we access the make, model, and year attributes of the "my_car" object using the dot notation. We also call the "get_description()" method of the "my_car" object to get a string containing the year, make, and model of the car.Adding Multiple Methods to a Class:
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
def circumference(self):
return 2 * 3.14 * self.radius
my_circle = Circle(5)
print(my_circle.area())
print(my_circle.circumference())
In this program, we have created a class named "Circle" that has an attribute named radius. We have also added two methods named area and circumference.
The area method calculates the area of the circle using the formula πr², where r is the radius. The circumference method calculates the circumference of the circle using the formula 2πr.
We create an object of the class named my_circle and pass the value 5 as the radius. We then call the area and circumference methods on my_circle and print the results.
No comments:
Post a Comment