当前分类:python>>正文

Python面向对象编程:创建可重用的代码

来源:互联网   更新时间:2023年7月10日  

Python 笔记

一、创建类和对象


class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed
        
    def bark(self):
        print("{} is barking!".format(self.name))
        
my_dog = Dog("Buddy", "Golden Retriever")
my_dog.bark()  # 输出:Buddy is barking!

二、继承和多态


class Animal:
    def __init__(self, name):
        self.name = name
        
    def speak(self):
        pass  # 抽象方法,需要子类实现
        
class Dog(Animal):
    def speak(self):
        return "woof"
        
class Cat(Animal):
    def speak(self):
        return "meow"
        
my_dog = Dog("Buddy")
my_cat = Cat("Whiskers")
print(my_dog.speak())  # 输出:woof
print(my_cat.speak())  # 输出:meow

三、封装和属性


class Car:
    wheels = 4  # 类属性
    
    def __init__(self, make, model):
        self._make = make  # 保护属性
        self.__model = model  # 私有属性
        self.__fuel = 0
        
    @property
    def make(self):
        return self._make
        
    @property
    def model(self):
        return self.__model
        
    @model.setter
    def model(self, value):
        self.__model = value
        
    @property
    def fuel(self):
        return self.__fuel
        
    def add_fuel(self, amount):
        self.__fuel += amount
        
my_car = Car("Toyota", "Corolla")
print(my_car.make)  # 输出:Toyota
print(my_car.model)  # 输出:Corolla
my_car.model = "Camry"
print(my_car.model)  # 输出:Camry
print(my_car.wheels)  # 输出:4
my_car.add_fuel(10)
print(my_car.fuel)  # 输出:10
本文固定链接:https://6yhj.com/leku-p-4742.html  版权所有,转载请保留本地址!
[猜你喜欢]

标签: 电商