☰分类导航

Python 编程/面向对象编程
课程进度 58% · 第7/11章第7/11章 · 标签 1/3
— 1 —

类的定义与使用

Python 是一种面向对象的语言,通过类来组织代码。


```python
class Student:
    """学生类"""

    # 类变量(所有实例共享)
    school = "Python编程学院"

    # 初始化方法(构造函数)
    def __init__(self, name, age, grade):
        self.name = name    # 实例变量
        self.age = age
        self.grade = grade

    # 实例方法
    def introduce(self):
        return f"我叫{self.name},今年{self.age}岁,{self.grade}年级"

    def study(self, hours):
        print(f"{self.name}学习了{hours}小时")

# 创建实例
student1 = Student("小明", 18, "高三")
print(student1.introduce())  # 我叫小明,今年18岁,高三年级
```
python
1
class Student:
2
"""学生类"""
3
 
4
# 类变量(所有实例共享)
5
school = "Python编程学院"
6
 
7
# 初始化方法(构造函数)
8
def __init__(self, name, age, grade):
9
self.name = name # 实例变量
10
self.age = age
11
self.grade = grade
12
 
13
# 实例方法
14
def introduce(self):
15
return f"我叫{self.name},今年{self.age}岁,{self.grade}年级"
16
 
17
def study(self, hours):
18
print(f"{self.name}学习了{hours}小时")
19
 
20
# 创建实例
21
student1 = Student("小明", 18, "高三")
22
print(student1.introduce()) # 我叫小明,今年18岁,高三年级
— 2 —

实例变量与类变量


```python
# 访问和修改属性
student1 = Student("小明", 18, "高三")
print(student1.school)    # Python编程学院
student1.name = "小红"    # 修改实例变量

# __dict__ 查看所有实例变量
print(student1.__dict__)

# 类方法
@classmethod
def get_school(cls):
    return cls.school

# 静态方法
@staticmethod
def validate_age(age):
    return 0 <= age <= 150

# property 装饰器
@property
def info(self):
    return f"{self.name}-{self.age}"

# setter
@info.setter
def info(self, value):
    self.name, self.age = value.split("-")
```
python
1
# 访问和修改属性
2
student1 = Student("小明", 18, "高三")
3
print(student1.school) # Python编程学院
4
student1.name = "小红" # 修改实例变量
5
 
6
# __dict__ 查看所有实例变量
7
print(student1.__dict__)
8
 
9
# 类方法
10
@classmethod
11
def get_school(cls):
12
return cls.school
13
 
14
# 静态方法
15
@staticmethod
16
def validate_age(age):
17
return 0 <= age <= 150
18
 
19
# property 装饰器
20
@property
21
def info(self):
22
return f"{self.name}-{self.age}"
23
 
24
# setter
25
@info.setter
26
def info(self, value):
27
self.name, self.age = value.split("-")