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
标签: 电商