类和对象

类和对象

一、类和对象

  • 类的意思:种类、分类类别

对象是特征与技能的结合体,我可能有身高体重、而你也有身高体重,所以你会说你像我,但是你一定不会说你像阿猫阿狗。并且我和你其实就可以说成是一类,而你和选课系统不能说是一类,因此给出类的定义:类就是一系列对象相似的特征与技能的结合体。

在现实世界中:先有一个个具体存在的对象,然后随着人类文明的发展才了分类的概念,既然现实世界中有类这个概念,Python程序中也一定有类这个概念,但是在Python程序中:必须先定义类,然后调用类来产生对象。

二、现实世界中定义类和对象

2.1 定义对象

就拿未来我们的选课系统来讲,我们先总结一套现实世界中的学生对象:

  • 对象1:
    • 特征:
      • 学校='hnnu'
      • 姓名='耗哥'
      • 年龄=18
      • 性别='male'
    • 技能:
      • 选课
  • 对象2:
    • 特征:
      • 学校='hnnu'
      • 姓名='猪哥'
      • 年龄=17
      • 性别='male'
    • 技能:
      • 选课
  • 对象3:
    • 特征:
      • 学校='hnnu'
      • 姓名='帅翔'
      • 年龄=19
      • 性别='female'
    • 技能:
      • 选课

2.2 定义对象

站在选课系统的角度,我们还可以总结现实世界中的学生类:

  • 学生类:
    • 相似的特征:
      • 学校='hnnu'
    • 相似的技能
      • 选课

三、程序中定义类和对象

3.1 定义类

class Student:
    school = 'hnnu'

    def choose_course(self):
        print("is choosing course")
  • 曾经定义函数,函数只检测语法,不执行代码,但是定义类的时候,类体代码会在类定义阶段就立刻执行,并且会产生一个类的名称空间,也就是说类的本身其实就是一个容器/名称空间,是用来存放名字的,这是类的用途之一

83-类与对象-名称空间.jpg?x-oss-process=style/watermark

# 查看类中属性和方法
print(Student.__dict__)

{'module': 'main', 'school': 'hnnu', 'choose_course': <function Student.choose_course at 0x00000170B6DE2400>, 'dict': <attribute 'dict' of 'Student' objects>, 'weakref': <attribute 'weakref' of 'Student' objects>, 'doc': None}

# 使用字典的方式,获取类属性值
print(Student.__dict__['school'])
print(Student.school)

hnnu

hnnu

# 通过字典的方式调用,类的方法
print(Student.__dict__['choose_course'])
try:
    # 使用字典调用,类中方法没有,给添加参数就会报错,所以通过类名调用的函数,必须与与函数中参数对应
    print(Student.__dict__['choose_course']())
except Exception as e:
    print(e)

<function Student.choose_course at 0x00000170B6DE2400>
choose_course() missing 1 required positional argument: 'self'

# 没有位置实参就会报错
print(Student.choose_course(12))

print(Student.choose_course)
print(Student.__dict__['choose_course'])

hnnu
is choosing course

# 添加属性
Student.country = 'China'
print(Student.__dict__["country"])
# 修改属性值
Student.country = "CHINA"
print(Student.__dict__["country"])
print(Student.country)

China
CHINA
CHINA

# 删除属性
del Student.school
print(Student.__dict__)

{'module': 'main', 'choose_course': <function Student.choose_course at 0x00000170B6DE2400>, 'dict': <attribute 'dict' of 'Student' objects>, 'weakref': <attribute 'weakref' of 'Student' objects>, 'doc': None}

3.2 定义对象

  • 调用类即可产生对象,调用类的过程,又称为类的实例化,实例化的结果称为类的对象/实例

83-类与对象-实例化.jpg?x-oss-process=style/watermark

# 调用类会得到一个返回值,该返回值就是类的一个具体存在的对象/实例
stu1 = Student()
print(stu1.school)

hnnu

stu2 = Student()
print(stu2.school)

hnnu

在当下的阶段,必将由程序员来主导,甚至比以往更甚。
原文地址:https://www.cnblogs.com/randysun/p/11414462.html