#1、设计一个类
class Student:
name = None
gender = None
nationality = None
age = None
#2、创建一个对象(类比生活中:打印一张登记表)
stu_1 = Student()
#3、对象属性进行赋值(类比生活中,填写表单)
stu_1.name = "Alex"
stu_1.gender = "男"
stu_1.nationality = "中国"
stu_1.age = 31
#4、获取对象中记录的信息
print(stu_1.name)
print(stu_1.gender)
print(stu_1.nationality)
print(stu_1.age)
"""
演示面向对象类中的成员方法定义和使用
"""
# 定义一个带有成员方法的类
class Student:
name = None # 学生的姓名
def say_hi(self):
print(f"大家好呀,我是{self.name},欢迎大家多多关照")
#在成员方法的内部,访问类的其他成员变量,需要在成员变量之前加self关键字
def say_hi2(self, msg): #传入参数
print(f"大家好,我是:{self.name},{msg}")
stu = Student()
stu.name = "jack"
stu.say_hi()
stu.say_hi2("哎哟不错哟")
stu2 = Student()
stu2.name = "alex"
stu2.say_hi2("小伙子我看好你")
"""
演示类和对象的关系,即面向对象的编程套路(思想)
"""
# 设计一个闹钟类
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()
"""
演示类的构造方法
"""
# 演示使用构造方法对成员变量进行赋值
# 构造方法的名称:__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)