寒假打卡18-2月4日
Python 面向对象编程(OOP)
在本篇文章中,我们将介绍 Python 的面向对象编程(OOP)概念,包括类与对象、继承与多态、魔法方法和装饰器等内容。这些知识将帮助你更好地组织和管理代码,提高代码的可维护性和可复用性。
1. 类与对象
定义类
使用 class
关键字定义类。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, my name is {self.name} and I am {self.age} years old."
创建对象
使用类名加上括号来创建对象。
person1 = Person("Alice", 30)
print(person1.greet()) # 输出: Hello, my name is Alice and I am 30 years old.
类属性与实例属性
类属性属于类本身,实例属性属于具体的对象。
class Dog:
species = "Canis familiaris" # 类属性
def __init__(self, name, age):
self.name = name # 实例属性
self.age = age
dog1 = Dog("Buddy", 5)
print(dog1.species) # 输出: Canis familiaris
print(dog1.name) # 输出: Buddy
2. 继承与多态
继承
继承是面向对象编程的重要特性,子类可以继承父类的属性和方法。
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclasses must implement this method")
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak()) # 输出: Woof!
print(cat.speak()) # 输出: Meow!
多态
多态是指不同对象可以通过相同的接口调用不同的方法。
def make_animal_speak(animal):
print(animal.speak())
make_animal_speak(dog) # 输出: Woof!
make_animal_speak(cat) # 输出: Meow!
3. 魔法方法
魔法方法是 Python 中以双下划线开头和结尾的方法,这些方法可以重载运算符,提供特定的功能。
__init__
方法
__init__
方法是构造方法,在创建对象时自动调用。
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
rect = Rectangle(4, 5)
print(rect.area()) # 输出: 20
__str__
方法
__str__
方法用于定义对象的字符串表示,可以通过 print
函数输出。
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def __str__(self):
return f"Rectangle(width={self.width}, height={self.height})"
rect = Rectangle(4, 5)
print(rect) # 输出: Rectangle(width=4, height=5)
__call__
方法
__call__
方法使对象可以像函数一样被调用。
class Adder:
def __init__(self, value):
self.value = value
def __call__(self, x):
return self.value + x
add5 = Adder(5)
print(add5(10)) # 输出: 15
4. 装饰器
装饰器是一个返回函数的高阶函数,可以用于修改函数或方法的行为。
函数装饰器
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.
类装饰器
class MyDecorator:
def __init__(self, func):
self.func = func
def __call__(self):
print("Something is happening before the function is called.")
self.func()
print("Something is happening after the function is called.")
@MyDecorator
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 的面向对象编程(OOP)概念,包括类与对象、继承与多态、魔法方法和装饰器等内容。通过学习这些知识,你能够更好地组织和管理代码,提高代码的可维护性和可复用性。接下来,我们将探讨 Python 并发编程的相关内容,敬请期待!