1. 定义一个简单的类
class Dog:def __init__(self, name):self.name = namedef bark(self):print(f"{self.name} says woof!")if __name__ == "__main__":my_dog = Dog("Rex")my_dog.bark()
2. 类的基本属性
class Car:def __init__(self, brand, model):self.brand = brandself.model = modeldef display_info(self):print(f"Brand: {self.brand}, Model: {self.model}")if __name__ == "__main__":my_car = Car("Toyota", "Corolla")my_car.display_info()
3. 类方法
class Circle:pi = 3.14def __init__(self, radius):self.radius = radiusdef area(self):return Circle.pi * self.radius * self.radiusif __name__ == "__main__":circle = Circle(5)print("Area:", circle.area())
4. 类变量和实例变量
class Employee:company_name = "ABC Corp"def __init__(self, name, age):self.name = nameself.age = agedef display_employee(self):print(f"Name: {self.name}, Age: {self.age}, Company: {Employee.company_name}")if __name__ == "__main__":emp = Employee("John", 30)emp.display_employee()
5. 类的继承
class Animal:def __init__(self, name):self.name = namedef speak(self):print("Animal sound")class Dog(Animal):def speak(self):print(f"{self.name} says woof!")if __name__ == "__main__":dog = Dog("Buddy")dog.speak()
6. 多重继承
class Walking:def walk(self):print("Walking")class Talking:def talk(self):print("Talking")class Robot(Walking, Talking):passif __name__ == "__main__":robot = Robot()robot.walk()robot.talk()
7. 使用super()调用父类方法
class Person:def __init__(self, name, age):self.name = nameself.age = agedef display(self):print(f"Name: {self.name}, Age: {self.age}")class Student(Person):def __init__(self, name, age, student_id):super().__init__(name, age)self.student_id = student_iddef display(self):super().display()print(f"Student ID: {self.student_id}")if __name__ == "__main__":student = Student("Alice", 20, "S12345")student.display()
8. 类的封装
class Account:def __init__(self):self.__balance = 0def deposit(self, amount):if amount > 0:self.__balance += amountelse:print("Invalid amount")def get_balance(self):return self.__balanceif __name__ == "__main__":acc = Account()acc.deposit(100)print("Balance:", acc.get_balance())
9. 静态方法
class MathOperations:@staticmethoddef add(a, b):return a + bif __name__ == "__main__":result = MathOperations.add(5, 3)print("Addition:", result)
10. 类方法
class Book:total_books = 0def __init__(self, title):self.title = titleBook.total_books += 1@classmethoddef get_total_books(cls):return cls.total_booksif __name__ == "__main__":book1 = Book("Python for Beginners")book2 = Book("Advanced Python")print("Total books:", Book.get_total_books())
11. 类的多态
class Shape:def area(self):passclass Rectangle(Shape):def __init__(self, width, height):self.width = widthself.height = heightdef area(self):return self.width * self.heightclass Circle(Shape):def __init__(self, radius):self.radius = radiusdef area(self):return 3.14 * self.radius * self.radiusif __name__ == "__main__":rect = Rectangle(3, 4)circ = Circle(5)shapes = [rect, circ]for shape in shapes:print("Area:", shape.area())
12. 操作符重载
class ComplexNumber:def __init__(self, real, imag):self.real = realself.imag = imagdef __add__(self, other):return ComplexNumber(self.real + other.real, self.imag + other.imag)def __str__(self):return f"{self.real} + {self.imag}i"if __name__ == "__main__":c1 = ComplexNumber(1, 2)c2 = ComplexNumber(3, 4)c3 = c1 + c2print("Sum:", c3)
13. 抽象类
from abc import ABC, abstractmethodclass Animal(ABC):@abstractmethoddef make_sound(self):passclass Dog(Animal):def make_sound(self):print("Woof")if __name__ == "__main__":dog = Dog()dog.make_sound()
14. 私有变量和方法
class MySecret:def __init__(self):self.__secret = "hidden value"def reveal_secret(self):print("Secret:", self.__secret)if __name__ == "__main__":obj = MySecret()obj.reveal_secret()# print(obj.__secret) # This will raise an AttributeError
15. 类的组合
class Engine:def start(self):print("Engine started")class Car:def __init__(self, engine):self.engine = enginedef start(self):self.engine.start()if __name__ == "__main__":engine = Engine()car = Car(engine)car.start()
16. 属性装饰器
class Temperature:def __init__(self, celsius):self.__celsius = celsius@propertydef fahrenheit(self):return (self.__celsius * 9/5) + 32if __name__ == "__main__":temp = Temperature(0)print("Fahrenheit:", temp.fahrenheit)
17. 析构方法
class Person:def __init__(self, name):self.name = nameprint(f"Person {self.name} created")def __del__(self):print(f"Person {self.name} destroyed")if __name__ == "__main__":p = Person("John")del p
18. 类的方法链调用
class Chain:def step_one(self):print("Step one")return selfdef step_two(self):print("Step two")return selfif __name__ == "__main__":obj = Chain()obj.step_one().step_two()
19. 自反性
class Reflexive:def __init__(self, value):self.value = valuedef __eq__(self, other):if isinstance(other, Reflexive):return self.value == other.valuereturn Falseif __name__ == "__main__":a = Reflexive(10)b = Reflexive(10)print("Are they equal?", a == b)
20. 类的例外处理
class NegativeAgeError(Exception):def __init__(self, message="Age cannot be negative"):self.message = messagesuper().__init__(self.message)class Person:def __init__(self, name, age):self.name = nameif age < 0:raise NegativeAgeError()self.age = ageif __name__ == "__main__":try:p = Person("John", -1)except NegativeAgeError as e:print(e)