一、初始对象
1.设计类
![](https://i-blog.csdnimg.cn/direct/7f2e0e7fc9fd4a3cbe124226168ca3b7.png)
2.创建对象
![](https://i-blog.csdnimg.cn/direct/baf56219ca874eb3bdb1614c4e432089.png)
3.对象属性赋值
![](https://i-blog.csdnimg.cn/direct/d51c4bbf031846ec912cb2e28cd0faac.png)
4.练习
class Student:
name = None
gender = None
nationality = None
native_place = None
age = None
stu_1 = Student()
stu_1.name = "招财"
stu_1.gender = "男"
stu_1.nationality = "中国"
stu_1.native_place = "贵州"
stu_1.age = 1.5
print(stu_1.name)
print(stu_1.gender)
print(stu_1.nationality)
print(stu_1.native_place)
print(stu_1.age
![](https://i-blog.csdnimg.cn/direct/f24dba9759ba4830a70f9231a6b1ed99.png)
二、成员方法
1.类定义
2.语法
- 类的行为
即类中的函数
def 方法名(self, 形参1, ...... , 形参N):
方法体
3.创建类对象的语法
4.练习
class Student:
name = None
def say_hi(self):
print(f"大家好,我是{self.name},欢迎大家多多关照")
def say_hi2(self, msg):
print(f"大家好,我是:{self.name},{msg}")
stu = Student()
stu.name = "招财"
stu.say_hi2("哎哟不错")
stu2 = Student()
stu2.name = "咪咪"
stu2.say_hi2("小伙纸。看好你")
![](https://i-blog.csdnimg.cn/direct/cd6b06e438744cd58e93f40a5937b607.png)
三、类和对象
1.实际事物
2.关系
3.练习
# 设计一个闹钟类
class Clock:
id = None
price = None
# 设计行为
def ring(self):
import winsound
winsound.Beep(2000,3000)
# 构建对象
clock1 = Clock()
clock1.id = "0033"
clock1.price = 99.99
print(f"闹钟ID:{clock1.id},价格:{clock1.price}")
clock1.ring()
clock2 = Clock()
clock2.id = "00333"
clock2.price = 999.99
print(f"闹钟ID:{clock2.id},价格:{clock2.price}")
clock2.ring()
![](https://i-blog.csdnimg.cn/direct/33abee55eccd4ecea84a78bc2527e4c6.png)
四、构造方法
1.__init__方法
- 构建类对象时,会自动执行
- 构建对象时,将参数自动传递给__init__方法
2.练习
# 构造方法的名字: __init__
class Student:
name = None
age = None
tel = None
def __init__(self, name, age, tel):
self.name = name
self.age =age
self.tel =tel
print("Student类创建了一个类对象")
stu = Student("招财", 1.5 , "18888888888")
print(stu.name, stu.age, stu.tel)
![](https://i-blog.csdnimg.cn/direct/b73826f239434c5bad28061534745173.png)