面向对象(1)

发布于:2024-08-13 ⋅ 阅读:(142) ⋅ 点赞:(0)

一、初始对象

  • 使用对象组织数据

1.设计类

  • 设计表格

2.创建对象

  • 打印生产表格

3.对象属性赋值

  • 填写表格

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

二、成员方法

1.类定义

  • 使用类去封装属性,并基于类创建出一个个对象来使用

2.语法

  • class 类名:
           类的属性
           类的行为

  • 类的属性
           即定义中的变量

  • 类的行为
          即类中的函数
          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("小伙纸。看好你")

三、类和对象

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()

四、构造方法

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)


网站公告

今日签到

点亮在社区的每一天
去签到