欢迎来到本站学习 Python 3 面向对象编程基础。以下是一些基础概念和示例,帮助你更好地理解面向对象编程。
类和对象
在 Python 中,类是创建对象的蓝图。对象是类的实例。
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says: Woof!"
# 创建对象
my_dog = Dog("Buddy", 5)
print(my_dog.bark()) # 输出: Buddy says: Woof!
继承
继承是面向对象编程中的一个重要概念。它允许一个类继承另一个类的属性和方法。
class Puppy(Dog):
def __init__(self, name, age, color):
super().__init__(name, age)
self.color = color
def play(self):
return f"{self.name} is playing with a ball."
# 创建对象
puppy = Puppy("Max", 2, "brown")
print(puppy.bark()) # 输出: Max says: Woof!
print(puppy.play()) # 输出: Max is playing with a ball.
多态
多态是指同一个方法在不同的对象上有不同的行为。
class Animal:
def speak(self):
return "Some sound"
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
# 创建对象
dog = Dog()
cat = Cat()
print(dog.speak()) # 输出: Woof!
print(cat.speak()) # 输出: Meow!
实例方法与类方法
实例方法是绑定到对象的,而类方法是绑定到类的。
class MyClass:
def __init__(self, value):
self.value = value
def instance_method(self):
return f"Instance method, value: {self.value}"
@classmethod
def class_method(cls):
return "Class method"
# 创建对象
obj = MyClass(10)
print(obj.instance_method()) # 输出: Instance method, value: 10
print(MyClass.class_method()) # 输出: Class method
装饰器
装饰器是用于修改函数或方法行为的函数。
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello() # 输出: Something is happening before the function is called. Hello! Something is happening after the function is called.
更多关于 Python 面向对象编程的内容,请访问 Python 面向对象编程教程。