Python面向对象编程基础
类的定义与使用
在 Python 中,类是一种用于定义对象的数据结构,它包含对象的状态(属性)和行为(方法)。通过类,可以实现代码的模块化和重用。
class Employee:
# 类变量
employee_type = "Full-time"
def __init__(self, name, position):
self.name = name # 实例变量
self.position = position
def display_info(self):
print(f"Name: {self.name}, Position: {self.position}")
@staticmethod
def company_policy():
return f"All employees are {Employee.employee_type}."
# 创建实例
emp1 = Employee("John", "Developer")
emp2 = Employee("Jane", "Designer")
print(emp1.name)
emp2.display_info()
print(Employee.company_policy())
实例属性的应用
实例属性是每个对象独有的数据成员,它们通常在构造函数中初始化。
class Student:
def __init__(self, student_id, grade):
self.student_id = student_id
self.grade = grade
def show_grade(self):
print(f"Student ID: {self.student_id}, Grade: {self.grade}")
student1 = Student(101, "A")
student2 = Student(102, "B")
student1.show_grade()
student2.grade = "A+"
student2.show_grade()
类属性与实例属性的区别
类属性是所有实例共享的,而实例属性则为每个实例单独存在。
class Vehicle:
vehicle_count = 0 # 类属性
def __init__(self, model):
Vehicle.vehicle_count += 1
self.model = model # 实例属性
def get_model(self):
return self.model
car1 = Vehicle("Sedan")
car2 = Vehicle("SUV")
print(Vehicle.vehicle_count) # 输出:2
print(car1.get_model()) # 输出:Sedan
实例方法详解
实例方法是与具体对象相关的方法,它们可以通过对象来调用,并能访问或修改对象的属性。
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def calc_area(self):
return self.width * self.height
rect = Rectangle(5, 10)
print(rect.calc_area()) # 输出:50
不同种类的方法
- 实例方法:需要通过实例调用,第一个参数是self。
- 类方法:第一个参数是cls,表示类本身。
- 静态方法:不依赖于类或实例,使用@staticmethod装饰器。
class Example:
@classmethod
def class_method(cls):
print(f"Called class method from {cls.__name__}")
@staticmethod
def static_method():
print("Called static method")
Example.class_method()
Example.static_method()