在Python中实现代码复用有几种常见的方法:
def say_hello(name):
print("Hello, " + name + "!")
say_hello("Alice")
say_hello("Bob")
class Person:
def __init__(self, name):
self.name = name
def say_hello(self):
print("Hello, " + self.name + "!")
person1 = Person("Alice")
person1.say_hello()
person2 = Person("Bob")
person2.say_hello()
import
语句可以在其他地方引用该模块,实现代码的复用。# module1.py
def say_hello(name):
print("Hello, " + name + "!")
# main.py
import module1
module1.say_hello("Alice")
module1.say_hello("Bob")
通过这些方法,可以实现代码的复用,减少重复编写相同功能的代码。