当前分类:python>>正文

Python类的面向对象编程实现方法

来源:互联网   更新时间:2023年8月28日  

Python 笔记

一、类的定义与实例化

class Car:
    def __init__(self, brand):
        self.brand = brand

    def drive(self):
        print(f"{self.brand} is driving.")
car = Car("Benz")
car.drive()   #输出 "Benz is driving."

二、私有属性和方法

class Car:
    def __init__(self, brand):
        self.__brand = brand

    def __drive(self):
        print(f"{self.__brand} is driving.")

    def run(self):
        self.__drive()

car = Car("Benz")
car.run()  #输出 "Benz is driving."
car.__drive()  #报错,实例无法访问私有方法

三、继承和多态

class Vehicle:
    def drive(self):
        print("Vehicle is driving.")

class Car(Vehicle):
    def drive(self):
        print("Car is driving.")

vehicle = Vehicle()
vehicle.drive()   #输出 "Vehicle is driving."

car = Car()
car.drive()   #输出 "Car is driving."
class Vehicle:
    def drive(self):
        print("Vehicle is driving.")

class Car(Vehicle):
    def drive(self):
        print("Car is driving.")

class Bike(Vehicle):
    def drive(self):
        print("Bike is driving.")

def drive_vehicle(vehicle):
    vehicle.drive()

vehicle = Vehicle()
car = Car()
bike = Bike()

drive_vehicle(vehicle)   #输出 "Vehicle is driving."
drive_vehicle(car)   #输出 "Car is driving."
drive_vehicle(bike)   #输出 "Bike is driving."

四、类的属性和方法装饰器

class Car:
    @property
    def brand(self):
        return self.__brand

    @brand.setter
    def brand(self, brand):
        self.__brand = brand

car = Car()
car.brand = "Benz"
print(car.brand)   #输出 "Benz"

五、魔术方法

class Car:
    def __init__(self, brand, color):
        self.brand = brand
        self.color = color

    def __str__(self):
        return f"{self.brand}({self.color})"

car = Car("Benz", "red")
print(car)   #输出 "Benz(red)"
本文固定链接:https://6yhj.com/leku-p-5608.html  版权所有,转载请保留本地址!
[猜你喜欢]

标签: 算法