面向?qū)ο缶幊蹋∣bject-Oriented Programming,OOP)是一種編程范式,它使用“對象”來表示現(xiàn)實世界中的事物,通過封裝、繼承和多態(tài)等特性來實現(xiàn)代碼的復(fù)用和模塊化。在Python中實現(xiàn)面向?qū)ο缶幊讨饕ㄒ韵聨讉€步驟:
class
關(guān)鍵字來定義一個類,類名通常使用大寫字母開頭的駝峰命名法。class ClassName:
# 類的屬性和方法
__init__
)來創(chuàng)建對象,并可以設(shè)置對象的屬性值。class MyClass:
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1
self.attribute2 = attribute2
# 創(chuàng)建對象
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):
# 方法的實現(xiàn)
pass
# 調(diào)用方法
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
關(guān)鍵字定義,并在類定義時指定父類。class ParentClass:
def __init__(self, attribute1):
self.attribute1 = attribute1
def my_method(self):
# 父類方法的實現(xiàn)
pass
class ChildClass(ParentClass):
def __init__(self, attribute1, attribute2):
super().__init__(attribute1)
self.attribute2 = attribute2
# 子類方法的實現(xiàn)
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())
# 調(diào)用不同類的對象的方法
dog = Dog("Buddy")
cat = Cat("Whiskers")
animal_speak(dog) # 輸出 "Woof!"
animal_speak(cat) # 輸出 "Meow!"