1. 类(Class)
类是对象的蓝图或模板。它定义了对象的属性和方法。
1 2 3 4 5 6 7 |
class Dog: def __init__(self, name, age): self.name = name self.age = age def bark(self): print(f"{self.name} is barking.") |
2. 对象(Object)
对象是类的实例。它是类的具体实现。
1 2 3 |
my_dog = Dog("Buddy", 3) print(f"My dog's name is {my_dog.name}.") # 输出: My dog's name is Buddy. my_dog.bark() # 输出: Buddy is barking. |
3. 属性(Attribute)
属性是对象的状态或数据。
1 2 3 4 5 6 7 |
class Car: def __init__(self, brand, model): self.brand = brand self.model = model my_car = Car("Toyota", "Corolla") print(f"My car is a {my_car.brand} {my_car.model}.") # 输出: My car is a Toyota Corolla. |
4. 方法(Method)
方法是定义在类中的函数,用来描述对象的行为。
1 2 3 4 5 6 7 8 9 |
class Circle: def __init__(self, radius): self.radius = radius def get_area(self): return 3.14 * self.radius ** 2 my_circle = Circle(5) print(f"Area of the circle: {my_circle.get_area()}") # 输出: Area of the circle: 78.5 |
5. 继承(Inheritance)
继承允许一个类继承另一个类的属性和方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Animal: def __init__(self, name): self.name = name def make_sound(self): print(f"{self.name} makes a sound.") class Cat(Animal): def make_sound(self): print(f"{self.name} meows.") my_cat = Cat("Whiskers") my_cat.make_sound() # 输出: Whiskers meows. |
6. 封装(Encapsulation)
封装是将数据和方法结合在一起,并对数据进行保护,不让外部直接访问。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class BankAccount: def __init__(self, balance): self.__balance = balance def deposit(self, amount): self.__balance += amount def get_balance(self): return self.__balance account = BankAccount(100) account.deposit(50) print(f"Balance: {account.get_balance()}") # 输出: Balance: 150 # print(account.__balance) # 这行代码会报错,因为 __balance 是私有的 |
7. 多态(Polymorphism)
多态允许不同的类以相同的接口来实现不同的功能。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Bird: def fly(self): print("Bird is flying.") class Airplane: def fly(self): print("Airplane is flying.") def make_it_fly(flying_object): flying_object.fly() bird = Bird() airplane = Airplane() make_it_fly(bird) # 输出: Bird is flying. make_it_fly(airplane) # 输出: Airplane is flying. |