write python class coding simple for beginner
Here is a simple Python class for beginners:
class Car:
# Constructor method
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
# Method to print car details
def print_details(self):
print(f"Make: {self.make}")
print(f"Model: {self.model}")
print(f"Year: {self.year}")
# Creating an instance of the Car class
my_car = Car("Toyota", "Corolla", 2021)
# Calling the print_details method
my_car.print_details()
In this example, we have created a class called Car with a constructor method that takes three parameters: make, model, and year. The constructor initializes these instance variables using the self keyword.
We have also defined a method called print_details() that prints the car's make, model, and year.
Finally, we create an instance of the Car class called my_car and call the print_details() method to print the car's details.
原文地址: https://www.cveoy.top/t/topic/yXf 著作权归作者所有。请勿转载和采集!