python进阶篇

1、简单的类举例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
"""
演示面向对象类中的成员方法定义和使用
"""
# 定义一个带有成员方法的类
class Student:
name = None # 学生的姓名

def say_hi(self):
print(f"大家好呀,我是{self.name},欢迎大家多多关照")

stu = Student()
stu.name = "周杰轮"
stu.say_hi()

stu2 = Student()
stu2.name = "林俊节"
stu2.say_hi()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
"""
演示类和对象的关系,即面向对象的编程套路(思想)
"""
# 设计一个闹钟类
class Clock:
id = None # 序列化
price = None # 价格


def ring(self):
import winsound
winsound.Beep(2000, 3000)

# 构建2个闹钟对象并让其工作
clock1 = Clock()
clock1.id = "003032"
clock1.price = 19.99
print(f"闹钟ID:{clock1.id},价格:{clock1.price}")
# clock1.ring()

clock2 = Clock()
clock2.id = "003033"
clock2.price = 21.99
print(f"闹钟ID:{clock2.id},价格:{clock2.price}")
clock2.ring()

2、构造函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
"""
演示类的构造方法
"""
# 演示使用构造方法对成员变量进行赋值
# 构造方法的名称:__init__

class Student:

def __init__(self, name, age ,tel):
self.name = name
self.age = age
self.tel = tel
print("Student类创建了一个类对象")

stu = Student("周杰轮", 31, "18500006666")
print(stu.name)
print(stu.age)
print(stu.tel)

python进阶篇
http://example.com/2025/05/20/python/python进阶篇/
Author
John Doe
Posted on
May 20, 2025
Licensed under