十个简单的Python类的例子
涵盖了基本的类概念、实例属性、方法及一些高级应用。
内容从浅入深。
例子 1:定义一个简单的类
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return "Woof!"
# 使用类
my_dog = Dog("Buddy")
print(my_dog.name) # 输出: Buddy
print(my_dog.bark()) # 输出: Woof!
例子 2:类属性和实例属性
class Car:
wheels = 4 # 类属性,所有实例共享
def __init__(self, color):
self.color = color # 实例属性,每个实例独有
# 使用类
my_car = Car("red")
print(my_car.wheels) # 输出: 4
print(my_car.color) # 输出: red
例子 3:私有属性和命名风格
class Account:
def __init__(self, owner, amount):
self.owner = owner
self.__amount = amount # 私有属性
def show_balance(self):
return f"{self.owner} has ${self.__amount} in the account."
# 使用类
account = Account("John", 500)
print(account.show_balance()) # John has $500 in the account.
例子 4:类方法和静态方法
class Circle:
pi = 3.14 # 类属性
def __init__(self, radius):
self.radius = radius
@classmethod
def from_diameter(cls, diameter):
return cls(diameter / 2)
@staticmethod
def is_valid_radius(radius):
return radius > 0
# 使用类
circle = Circle.from_diameter(10)
print(circle.radius) # 输出: 5.0
print(Circle.is_valid_radius(5)) # 输出: True
例子 5:继承
class Animal:
def speak(self):
return "Some sound"
class Cat(Animal):
def speak(self):
return "Meow"
# 使用类
my_cat = Cat()
print(my_cat.speak()) # 输出: Meow
例子 6:多态和抽象类
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow"
# 使用类
animals = [Dog(), Cat()]
for animal in animals:
print(animal.speak()) # 输出: Woof! 和 Meow!
例子 7:属性装饰器
class Celsius:
def __init__(self, temperature=0):
self._temperature = temperature
@property
def temperature(self):
return self._temperature
@temperature.setter
def temperature(self, value):
if value < -273.15:
raise ValueError("Temperature below -273.15 is not possible")
self._temperature = value
# 使用类
weather = Celsius()
weather.temperature = 25
print(weather.temperature) # 输出: 25
try:
weather.temperature = -300
except ValueError as e:
print(e) # 输出: Temperature below -273.15 is not possible
例子 8:重载运算符
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __str__(self):
return f"Vector({self.x}, {self.y})"
# 使用类
v1 = Vector(2, 4)
v2 = Vector(1, 3)
print(v1 + v2) # 输出: Vector(3, 7)
例子 9:多重继承
class Engine:
def start(self):
return "Engine starting"
class Camera:
def click(self):
return "Clicking photo"
class Phone(Engine, Camera):
def make_call(self):
return "Making call"
# 使用类
smartphone = Phone()
print(smartphone.start()) # 输出: Engine starting
print(smartphone.click()) # 输出: Clicking photo
例子 10:复合
class Engine:
def start(self):
return "Engine has been started"
class Car:
def __init__(self):
self.engine = Engine()
def start(self):
return self.engine.start()
# 使用类
my_car = Car()
print(my_car.start()) # 输出: Engine has been started