面向對象編程(Object-Oriented Programming,OOP)是一種編程范式,它使用“對象”來表示現實世界中的事物,通過封裝、繼承和多態等特性來實現代碼的復用和模塊化。在Python中實現面向對象編程主要包括以下幾個步驟:
class
關鍵字來定義一個類,類名通常使用大寫字母開頭的駝峰命名法。class ClassName:
# 類的屬性和方法
__init__
)來創建對象,并可以設置對象的屬性值。class MyClass:
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1
self.attribute2 = attribute2
# 創建對象
my_object = MyClass("value1", "value2")
class MyClass:
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1
self.attribute2 = attribute2
# 訪問和修改屬性值
my_object.attribute1 = "new_value"
class MyClass:
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1
self.attribute2 = attribute2
def my_method(self):
# 方法的實現
pass
# 調用方法
my_object.my_method()
class MyClass:
def __init__(self, attribute1, attribute2):
self.__attribute1 = attribute1
self.__attribute2 = attribute2
def get_attribute1(self):
return self.__attribute1
def set_attribute1(self, value):
if isinstance(value, str):
self.__attribute1 = value
# 其他屬性和方法
class
關鍵字定義,并在類定義時指定父類。class ParentClass:
def __init__(self, attribute1):
self.attribute1 = attribute1
def my_method(self):
# 父類方法的實現
pass
class ChildClass(ParentClass):
def __init__(self, attribute1, attribute2):
super().__init__(attribute1)
self.attribute2 = attribute2
# 子類方法的實現
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
def animal_speak(animal):
print(animal.speak())
# 調用不同類的對象的方法
dog = Dog("Buddy")
cat = Cat("Whiskers")
animal_speak(dog) # 輸出 "Woof!"
animal_speak(cat) # 輸出 "Meow!"