[100 days proficient in python] Day13: Object-oriented programming_polymorphism and encapsulation, actual simulation of the ticket page of the automatic ticket vending machine in the cinema

Table of contents

1 Polymorphism (Polymorphism)

2 Encapsulation (Encapsulation)

3 summary

4 Actual Combat: Simulating the ticket page of the automatic ticket vending machine in the cinema


In Python, polymorphism and encapsulation are two important concepts of object-oriented programming.

1 Polymorphism (Polymorphism)

        Polymorphism means that the same method can produce different behaviors according to different object types. In Python, polymorphism is achieved through dynamic binding of methods, that is, method calls are determined at runtime based on the type of the object. This makes the code more flexible and can handle different types of objects without caring about the specific type of the object.

class Animal:
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

def make_sound(animal):
    return animal.speak()

dog = Dog()
cat = Cat()

print(make_sound(dog))  # 输出:Woof!
print(make_sound(cat))  # 输出:Meow!

In the above example, we defined a base class Animal and two subclasses Dog and Cat, both of which override the speak method of the base class. Then, we define a make_sound function that takes a parameter of type Animal and calls its speak method. When we pass in different types of objects (Dog and Cat) to the make_sound function, due to the polymorphic feature, the function will call different speak methods according to the type of the object passed in, realizing polymorphism.

2 Encapsulation (Encapsulation)

         Encapsulation refers to encapsulating data and operations on data in an object, hiding internal implementation details from the outside. In Python, encapsulation is achieved by defining data and methods in classes and using access modifiers to control external access to internal data. Encapsulation can ensure the security and integrity of data, and provide a good abstraction, so that external code can only access and manipulate data through the public interface of the class.

Example:

class Car:
    def __init__(self, make, model):
        self._make = make
        self._model = model
        self._speed = 0

    def accelerate(self, amount):
        self._speed += amount

    def brake(self, amount):
        self._speed -= amount

    def get_speed(self):
        return self._speed

car = Car("Toyota", "Corolla")

car.accelerate(50)
print(car.get_speed())  # 输出:50

# 尝试直接访问对象的内部数据,将会得到错误
# print(car._speed)  # 错误:AttributeError: 'Car' object has no attribute '_speed'

In the above example, we defined a Car class that encapsulates the data and methods of the vehicle. Use private variables (starting with a single underscore) to represent internal data, and public methods to manipulate the data. In this way, external code cannot directly access the internal data of the object, and can only access and manipulate data through public methods, which realizes encapsulation.

3 summary

Polymorphism and encapsulation are two important concepts in object-oriented programming.

Polymorphism enables the same method to handle different types of objects, increasing code flexibility and reusability.

Encapsulation encapsulates data and methods in objects, hides internal implementation details from the outside, ensures data security and integrity, and provides a good abstraction.

In Python, we can achieve polymorphism and encapsulation through inheritance and access modifiers.

4 Actual Combat: Simulating the ticket page of the automatic ticket vending machine in the cinema

In order to simulate the ticket page of a movie theater's automatic ticket vending machine, we can create a simple Python program that allows users to select movies, seats, and the number of tickets to buy. Here is a basic example:

class Movie:
    def __init__(self, title, showtimes, available_seats):
        self.title = title
        self.showtimes = showtimes
        self.available_seats = available_seats

class TicketMachine:
    def __init__(self):
        self.movies = []
        self.current_movie = None
        self.current_showtime = None
        self.selected_seats = []

    def add_movie(self, movie):
        self.movies.append(movie)

    def show_movies(self):
        print("Movies available:")
        for idx, movie in enumerate(self.movies, start=1):
            print(f"{idx}. {movie.title}")

    def select_movie(self, movie_idx):
        self.current_movie = self.movies[movie_idx - 1]
        self.show_movie_showtimes()

    def show_movie_showtimes(self):
        print(f"Showtimes for '{self.current_movie.title}':")
        for idx, showtime in enumerate(self.current_movie.showtimes, start=1):
            print(f"{idx}. {showtime}")

    def select_showtime(self, showtime_idx):
        self.current_showtime = self.current_movie.showtimes[showtime_idx - 1]
        self.show_available_seats()

    def show_available_seats(self):
        print("Available seats:")
        for seat in self.current_movie.available_seats:
            if seat not in self.selected_seats:
                print(seat)

    def select_seats(self, seats):
        self.selected_seats.extend(seats)

    def buy_tickets(self):
        total_price = len(self.selected_seats) * 10  # 假设每张票价格为10元
        print(f"Total price: {total_price} yuan")
        self.current_movie.available_seats = [seat for seat in self.current_movie.available_seats if seat not in self.selected_seats]
        print("Tickets purchased successfully!")

if __name__ == "__main__":
    # 创建电影对象
    movie1 = Movie("Movie 1", ["10:00 AM", "2:00 PM", "6:00 PM"], ["A1", "A2", "B1", "B2"])
    movie2 = Movie("Movie 2", ["11:00 AM", "3:00 PM", "7:00 PM"], ["C1", "C2", "D1", "D2"])

    # 创建售票机对象
    ticket_machine = TicketMachine()
    ticket_machine.add_movie(movie1)
    ticket_machine.add_movie(movie2)

    # 用户选票流程
    print("Welcome to the Ticket Machine!")
    ticket_machine.show_movies()
    movie_choice = int(input("Select a movie (enter the movie number): "))
    ticket_machine.select_movie(movie_choice)
    showtime_choice = int(input("Select a showtime (enter the showtime number): "))
    ticket_machine.select_showtime(showtime_choice)
    print("Select your seats (enter seat numbers separated by spaces):")
    seats_choice = input().split()
    ticket_machine.select_seats(seats_choice)
    ticket_machine.buy_tickets()

Create tickets.py file in python IDLE, run the above code, the result is as follows:

Please note that the above example is a simple simulation and does not have the actual ticket purchase function, it is only used to demonstrate the process. In practical applications, we need to interact with databases or other systems, and add more complex functions, such as user login, payment, etc. This example is for reference only, you can expand it according to your actual needs. 

Guess you like

Origin blog.csdn.net/qq_35831906/article/details/131891022