在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")
通過這些方法,可以實現代碼的復用,減少重復編寫相同功能的代碼。