📚 前端知识库
点击卡片按钮,探索更多内容
Unit Orientation
Welcome
Welcome to Programming 2. This is an advanced Python programming unit designed to build upon the foundational knowledge that you acquired in Programming 1, which introduced the basics of Python programming. My name is Carolyn Seton and I am the unit assessor for Programming 2. I am passionate about all things programming and am looking forward to meeting you all through out the term.
欢迎学习编程2。这是一门高级 Python 编程课程,旨在建立在编程1中所获得的基础知识之上,编程1介绍了 Python 编程的基础知识。我是 Carolyn Seton,是编程2的单元评估员。我对编程充满热情,期待在整个学期中与大家见面。
What is this unit about?
This unit is designed to give you an understanding of more complex concepts in Python that enable the development of sophisticated and efficient programs using an object-oriented approach (OOP). OOP is a cornerstone of modern software development, enabling programmers to create modular, reusable, and scalable code. This knowledge is crucial for writing efficient code and for understanding how most modern software systems are structured and developed.
本课程旨在让您理解 Python 中更复杂的概念,能够使用面向对象方法开发复杂高效的程序。面向对象编程是现代软件开发的基石,使程序员能够创建模块化、可重用和可扩展的代码。这些知识对于编写高效代码以及理解大多数现代软件系统的结构和开发方式至关重要。
In this unit you will learn how to model real-world concepts using classes and objects and design elegant solutions. Throughout the unit, you’ll work with essential data structures like lists, sets, tuples, and dictionaries, and learn how to handle exceptions and encapsulate data for robust secure code. In the final modules you will explore Python libraries and apply your knowledge to build complete Python programs.
在本课程中,您将学习如何使用类和对象对现实世界的概念进行建模,并设计优雅的解决方案。在整个课程中,您将使用列表、集合、元组和字典等基本数据结构,并学习如何处理异常和封装数据以编写健壮安全的代码。在最后的模块中,您将探索 Python 库并运用所学知识构建完整的 Python 程序。
For students undertaking the software development major Programming 2 will provide you with the foundation required to explore Python’s extensive libraries and frameworks across various applications, from web development to machine learning. The fundamentals learned in this unit will also allow you to transition into more advanced programming units and other programming languages with ease.
对于攻读软件开发专业的学生,编程2将为您提供所需的基础,使您能够探索 Python 在各种应用中的广泛库和框架,从 Web 开发到机器学习。在本课程中学到的基础知识还将使您能够轻松过渡到更高级的编程课程和其他编程语言。
For students undertaking other majors, having a solid understanding in Python is crucial in fields like networking, cybersecurity, and data analysis due to Python’s versatility, ease of use, and the extensive support it offers through libraries and frameworks tailored to these domains. For networking, Python automates and simplifies tasks such as device configuration and network analysis. In cybersecurity, it’s used for developing scripts for penetration testing, vulnerability scans, and automation of security incident responses. For data analysis, Python’s powerful libraries like Pandas and NumPy enable efficient data manipulation and analysis, making it an indispensable tool for extracting insights from large datasets.
对于攻读其他专业的学生来说,扎实掌握 Python 在网络安全、数据分析和网络工程等领域至关重要,这得益于 Python 的多功能性、易用性以及通过针对这些领域的库和框架提供的广泛支持。在网络工程方面,Python 可以自动化和简化设备配置和网络分析等任务。在网络安全方面,它用于开发渗透测试、漏洞扫描和安全事件响应自动化的脚本。对于数据分析,Python 强大的库(如 Pandas 和 NumPy)支持高效的数据处理和分析,使其成为从大型数据集中提取见解的不可或缺的工具。
Unit topics
The following topics are covered in Programming 2:
编程2涵盖以下主题:
- Module 1: Introduction to Classes and Objects
- Module 2: Advanced Class Design
- Module 3: Objects, Exceptions, and Lists
- Module 4: Sets, Tuples, and Dictionaries
- Module 5: Building Python Programs 1
- Module 6: Building Python Programs 2
- 模块1:类和对象入门
- 模块2:高级类设计
- 模块3:对象、异常和列表
- 模块4:集合、元组和字典
- 模块5:构建 Python 程序 1
- 模块6:构建 Python 程序 2
Outcomes of the unit
After completing the learning activities in the unit, you will be able to:
完成本单元的学习活动后,您将能够:
- Modify and expand short object-oriented programs that use standard control structures
- Design, implement, test, and debug simple programs in an object-oriented programming language
- Demonstrate how to use class mechanisms to support encapsulation and efficient code
- Analyse and determine appropriate data structures and iteration methods to support a solution.
- 修改和扩展示使用标准控制结构的短面向对象程序
- 使用面向对象编程语言设计、实现、测试和调试简单程序
- 演示如何使用类机制支持封装和高效代码
- 分析并确定合适的数据结构和迭代方法来支持解决方案
How will this unit be taught?
This unit will be taught over six weeks (six modules) that follow the Southern Cross Model. You will work through one module comprised of self-paced material, a workshop and a tutorial each week. It is important to complete the learning activities, because these are designed to help you prepare for the assessment. Contributing to class discussion forums and other group activities will provide more opportunities to learn and help your fellow students.
本课程将按照南十字星模式进行为期六周(六个模块)的教学。您每周将完成一个模块,包括自主学习材料、研讨会和辅导课。完成学习活动非常重要,因为这些活动旨在帮助您为评估做准备。参与课堂讨论论坛和其他小组活动将提供更多学习机会并帮助您的同学。
This mode of learning may seem more intensive than you are used to, so it is important to keep up with the weekly modules. Students are expected to spend up to 20 hours per week progressing through the self-paced material and preparing for assessments, plus there are three hours of scheduled class time:
这种学习模式可能比您习惯的方式更加密集,因此跟上每周的模块非常重要。学生每周预计花费最多20小时学习自主学习材料和准备评估,此外还有三小时的正课时间:
- One 2-hour tutorial each week
- One 1-hour workshop each week
- 每周一次2小时的辅导课
- 每周一次1小时的研讨会
Tutorials
We will meet together as a class at scheduled class tutorial times and you are highly encouraged to attend. For students enrolled online, there will be online tutorials that will run in Blackboard Collaborate Ultra. The tutorial activities are vital in helping you understand the content and complete the assessment tasks. Prepare for the tutorials by completing the module preparatory activities, and bring your questions and ideas to share with the class.
我们将在预定的课堂辅导时间集体见面,强烈建议您参加。对于在线注册的学生,将有在 Blackboard Collaborate Ultra 中进行的在线辅导课。辅导活动对于帮助您理解内容和完成评估任务至关重要。通过完成模块准备活动来为辅导课做准备,并带着您的问题和想法与全班分享。
Workshops
The weekly workshops will be run online via Blackboard Collaborate Ultra and everyone is expected to attend. These workshops will cover more detail about how to prepare for your assessments as well as opportunities to ask questions.
每周的研讨会将通过 Blackboard Collaborate Ultra 在线进行,希望大家都能参加。这些研讨会将更详细地介绍如何为评估做准备,并提供提问的机会。
Discussion boards
There is a Discussion Board for the unit. You can use the Discussion Board to ask questions about the unit; in this way everyone gets the benefit of the conversation.
本课程设有讨论板。您可以使用讨论板提出关于课程的问题;这样每个人都能从对话中受益。
How will this unit be assessed?
There are three (3) assessment tasks to be completed in this unit. Please refer to the Unit Profile and the Assessment Tasks and Submission left menu links to view the due dates, assessment weightings and other relevant information. Review these links now so you can start thinking and planning how you will complete the assessment. Assessment will also be discussed in the weekly workshops.
本单元需要完成三(3)项评估任务。请参阅单元简介和左侧菜单中的评估任务与提交链接,查看截止日期、评估权重和其他相关信息。请立即查看这些链接,以便开始思考和规划如何完成评估。每周的研讨会也将讨论评估相关事宜。
What resources will I need?
No specific resources are required for this unit.
本单元不需要特定资源。
How should I plan for study?
Think about when you work best, and factor time in for the preparation you will need for the assessment tasks. Take note of your tutorial and workshop times, and factor in time to complete any preparation tasks. On average you will need 20 hours per week for each unit you are studying. Also check the key dates on the SCU Calendar.
想一想您什么时候工作效率最高,并为评估任务的准备工作预留时间。记下您的辅导课和研讨会时间,并为完成任何准备任务留出时间。平均而言,您所学的每个单元每周需要20小时。同时请查看 SCU 校历上的重要日期。
Where can I go for help?
See the Learning Help section in your left menu for support options. The Learning Support link provides access to the Student Learning Zone, which provides support workshops, student appointments and resources for study including referencing and academic integrity. The Library can assist with libguides, catalogue searches, accessing readings and other resources.
请查看左侧菜单中的学习帮助部分以获取支持选项。学习支持链接提供学生学习区的访问权限,该区提供支持研讨会、学生预约和学习资源,包括引用和学术诚信。图书馆可以提供指南、目录搜索、访问阅读材料和其他资源的帮助。
What next?
- Become familiar with this unit website
- Introduce yourself on the Discussion Forum
- Download and install Python and a suitable IDE
- Review the information about Assessment for this unit
- Make sure you are ready for participation in online meetings and activities
- Start planning your study schedule
- Start working on Module 1
- Bring any questions to our first class tutorial
- 熟悉本单元网站
- 在讨论论坛上自我介绍
- 下载并安装 Python 和合适的 IDE
- 查看本单元的评估信息
- 确保您已准备好参与在线会议和活动
- 开始规划您的学习计划
- 开始学习模块1
- 带着问题来到我们的第一堂辅导课
Module 1: Introduction to Classes and Objects
模块1:类和对象入门
Module overview
Classes and objects are the foundation of object-oriented programming (OOP). This module introduces these fundamental concepts in Python, helping you understand how they enable the creation of well-structured, reusable, and maintainable code. Whether you’re looking to manage complex software systems or simply aiming to organise your code more effectively, understanding classes and objects is a crucial step in your Python programming journey. Through practical examples and exercises, this module will walk you through these concepts, illustrating how they come together to provide a powerful approach to programming in Python. If you struggle with any aspect of the activities, please let the lecturer know so that they can be covered in the tutorial.
类和对象是面向对象编程(OOP)的基础。本模块介绍 Python 中的这些基本概念,帮助您理解它们如何实现结构良好、可重用和可维护的代码。无论您是想管理复杂的软件系统,还是仅仅希望更有效地组织代码,理解类和对象都是您 Python 编程之旅中的关键一步。通过实际示例和练习,本模块将引导您掌握这些概念,展示它们如何共同提供一种强大的 Python 编程方法。如果您在活动的任何方面遇到困难,请告知讲师,以便在辅导课中讲解。
Module purpose
The module covers the following Unit Learning Outcomes:
本模块涵盖以下单元学习成果:
- ULO1 – modify and expand short object-oriented programs that use standard control structures
- ULO1 – 修改和扩展示使用标准控制结构的短面向对象程序
- ULO2 – design implement, test, and debug simple programs in an object-orientated programming language
- ULO2 – 使用面向对象编程语言设计、实现、测试和调试简单程序
At the end of this module, you will be able to define and demonstrate the following concepts:
在本模块结束时,您将能够定义和演示以下概念:
- Built-in classes and objects —— 内置类和对象
- User-defined classes and objects —— 用户定义的类和对象
- Instance and class attributes —— 实例属性和类属性
- Constructors —— 构造函数
- Mutability —— 可变性
- Functions and methods —— 函数和方法
Introduction
Procedural programming
In Programming 1, we covered the fundamental building blocks of Python programs. This included concepts like printing, variables, strings, operators, conditional statements, loops, file handling, and user-defined functions. When applying these concepts, our programs were developed using a procedural approach.
在编程1中,我们学习了 Python 程序的基本构建块。这包括打印、变量、字符串、运算符、条件语句、循环、文件处理和用户自定义函数等概念。在应用这些概念时,我们的程序是使用过程式方法开发的。
Procedural programming is based on the concept of procedure calls (functions). It is a programming paradigm that uses a linear or top-down approach and focuses on the procedure (steps or functions) to operate on data. Procedural programs are typically structured as a sequence of instructions or commands.
过程式编程基于过程调用(函数)的概念。它是一种使用线性或自顶向下方法的编程范式,专注于操作数据的过程(步骤或函数)。过程式程序通常被结构化为一系列指令或命令。
Procedural programming is often used for straightforward, sequential tasks requiring a clear series of steps to perform an operation. It can be simpler and easier to understand for linear, step-by-step processes. Procedural programming is also more straightforward and easier to understand for beginners when they’re learning all the fundamental building blocks required to write a program. However, for complex systems, procedural programming can lead to “spaghetti code” and is not recommended.
过程式编程通常用于需要明确步骤顺序执行操作的简单任务。对于线性的、逐步的过程来说,它更简单、更容易理解。对于初学者来说,过程式编程在学习编写程序所需的所有基本构建块时也更直接、更容易理解。然而,对于复杂的系统,过程式编程可能导致”意大利面条式代码”,因此不推荐使用。
Object-oriented programming
In the final module of Programming 1, we briefly introduced classes, objects, and object-oriented programming (OOP).
在编程1的最后一个模块中,我们简要介绍了类、对象和面向对象编程(OOP)。
OOP is based on the concept of objects, which contain data and methods to operate on that data. Programs are designed as a collection of objects that interact with each other. Each object represents an instance of a class and has its own attributes (state) and methods (behaviour).
OOP 基于对象的概念,对象包含数据以及操作这些数据的方法。程序被设计为相互交互的对象的集合。每个对象代表一个类的实例,并具有自己的属性(状态)和方法(行为)。
OOP is ideal for applications with complex architectures and behaviours, like GUIs, real-world simulations, and large-scale software systems. OOP can make managing complexity, reusing code, and handling large-scale software architecture easier.
OOP 非常适合具有复杂架构和行为的应用程序,如图形用户界面、真实世界模拟和大规模软件系统。OOP 可以使管理复杂性、重用代码和处理大规模软件架构变得更加容易。
In this module and the following module, we will cover classes and objects extensively and transition from a procedural programming approach to an object-oriented programming approach.
在本模块和下一个模块中,我们将广泛介绍类和对象,并从过程式编程方法过渡到面向对象编程方法。
Classes and Objects
Let’s take a minute to recap the definition of classes and objects and cover the vocabulary we will need for the remainder of the module and the following module.
让我们花点时间回顾一下类和对象的定义,并介绍本模块和下一模块所需的词汇。
📝 Try the following fill in the blanks to test your knowledge:
A class is a blueprint for creating _____
A class defines the attributes and _____ of objects.
Objects are instances of _____
For example, if you have a class Dog, you can create multiple instances (objects) of this class, like dog1 and dog2, each representing a specific dog with its own attributes and methods.
例如,如果您有一个 Dog 类,您可以创建该类的多个实例(对象),如 dog1 和 dog2,每个实例代表一个具有自己属性和方法的特定狗。
Here are the key aspects of classes in Python:
以下是 Python 中类的关键方面:
属性
方法
__init__ 方法
继承
封装
实例
实例化
Attributes are variables that belong to a class. They represent the state or data of the objects created from the class.
属性是属于类的变量。它们表示从类创建的对象的 state 或数据。
For example, a Dog class might have attributes like name, age, and breed.
例如,一个 Dog 类可能有 name、age 和 breed 等属性。
In Programming 1, we covered functions. You will recall that a function is a block of code that performs a specific task. They can have parameters, perform operations, and return a result. Functions in Python are defined using the def keyword.
在编程1中,我们学习了函数。您应该记得函数是执行特定任务的代码块。它们可以有参数、执行操作并返回结果。Python 中的函数使用 def 关键字定义。
We briefly introduced methods in Programming 1. A method in Python is similar to a function but is associated with an object or class. Methods are defined within a class and are meant to operate on the attributes contained within that class (the object’s state). Methods define the behaviour of the objects.
我们在编程1中简要介绍了方法。Python 中的方法类似于函数,但与对象或类相关联。方法在类内部定义,用于操作该类中包含的属性(对象的状态)。方法定义了对象的行为。
For instance, a Dog class might have methods like bark or walk.
例如,Dog 类可能有 bark 或 walk 等方法。
To summarise, functions are standalone constructs, while methods are associated with objects and classes.
总之,函数是独立的构造,而方法与对象和类相关联。
The __init__ method is a special method that gets called when a new object of the class is created. It is commonly used to initialise the class’s attributes. It’s the Python equivalent of a constructor in other object-oriented languages.
__init__ 方法是一个特殊方法,在创建类的新对象时被调用。它通常用于初始化类的属性。它是 Python 中与其他面向对象语言中的构造函数等效的内容。
Inheritance allows a new class to inherit attributes and methods from an existing class. The new class is called a subclass or child class, and the class it inherits from is called the superclass or parent class. This promotes code reusability. We will cover inheritance in the next module.
继承允许新类从现有类继承属性和方法。新类称为子类或派生类,它继承的类称为超类或父类。这促进了代码的可重用性。我们将在下一模块中介绍继承。
Encapsulation is the concept of bundling attributes and methods that act on the data into a single unit or class. Encapsulation also restricts direct access to some of a class’s components, preventing accidental interference and misuse of the methods and data. We will cover encapsulation in the next module.
封装是将属性和操作数据的方法捆绑到单个单元或类中的概念。封装还限制对类某些组件的直接访问,防止意外干扰和滥用方法及数据。我们将在下一模块中介绍封装。
Another way programmers talk about objects is to say that an object is an instance of a particular class. The terms instance and object can be used interchangeably.
程序员谈论对象的另一种方式是,对象是特定类的实例。术语实例和对象可以互换使用。
Creating an instance of a class is known as instantiation. This is when a class defines is used to create a concrete object.
创建类的实例称为实例化。这时使用类定义来创建一个具体的对象。
📝 Multiple Choice Questions / 选择题
1. What are attributes in the context of object-oriented programming?
在面向对象编程中,什么是属性?
2. In Python, how are functions defined, and what keyword is used for it?
在 Python 中,函数是如何定义的,使用什么关键字?
3. How are methods different from functions in Python?
在 Python 中,方法和函数有何不同?
4. What does the __init__ method do in a Python class?
__init__ 方法在 Python 类中有什么作用?
5. What is the purpose of inheritance in object-oriented programming?
继承在面向对象编程中的目的是什么?
6. What is encapsulation in the context of object-oriented programming?
在面向对象编程中,什么是封装?
7. What is another term used interchangeably with “object” in object-oriented programming?
在面向对象编程中,与”对象”可以互换使用的另一个术语是什么?
8. What is instantiation in the context of object-oriented programming?
在面向对象编程中,什么是实例化?
9. Which method is commonly used to initialize a class’s attributes in Python?
在 Python 中,哪个方法通常用于初始化类的属性?
10. What is the primary advantage of encapsulation in object-oriented programming?
封装在面向对象编程中的主要优势是什么?
Built-in Classes
Python comes with various built-in classes that are used frequently in various types of programs and you have been using them extensively in Programming 1. Some of the most common built-in classes that you would be aware of include:
Python 带有各种内置类,在各种类型的程序中频繁使用,您在编程1中已经广泛使用过它们。您应该知道的一些最常见的内置类包括:
- int: Represents integer numbers. / 表示整数。
- float: Represents floating-point numbers. / 表示浮点数。
- bool: Represents a Boolean value, True or False. / 表示布尔值 True 或 False。
- str: Represents a string of characters. / 表示字符串。
- list: Represents a mutable sequence of items. / 表示可变的项目序列。
- file: Used to create a file object for file handling (reading, writing). / 用于创建文件处理(读取、写入)的文件对象。
As we covered strings extensively, let’s use strings as an example.
由于我们广泛介绍了字符串,让我们以字符串为例。
some_string = "I am a string"
print(type(some_string))
print(dir(str))
print(some_string.__add__("!"))
print(some_string.__sizeof__())
print(some_string.startswith("I"))
In your IDE, create a new Python file and run the following code.
在您的 IDE 中,创建一个新的 Python 文件并运行以下代码。
In the terminal, you will see the following output.
在终端中,您将看到以下输出。
You should be familiar with the first line of code that declares a string.
您应该熟悉声明字符串的第一行代码。
On the second line of code, you should be familiar with print. This line prints the type of the variable some_string. The type() function in Python is used to get the type of an object. In this case, type(some_string) returns <class ‘str’>, indicating that some_string is an instance of the str class.
在第二行代码中,您应该熟悉 print。这一行打印变量 some_string 的类型。Python 中的 type() 函数用于获取对象的类型。在这种情况下,type(some_string) 返回 <class ‘str’>,表示 some_string 是 str 类的一个实例。
Add the following line of code and rerun the program.
添加以下代码行并重新运行程序。
The dir() function is a built-in Python function that returns a sorted list of names of the attributes and methods of any object. By passing str to dir(), it lists everything that can be done with a string object, including all string methods like .lower(), .upper(), .strip(), and many others.
dir() 函数是一个 Python 内置函数,它返回任何对象的属性和方法名称的排序列表。通过将 str 传递给 dir(),它列出了可以对字符串对象执行的所有操作,包括所有字符串方法,如 .lower()、.upper()、.strip() 等。
Activity 3: String methods
Strings are used in just about every program you will write. As it’s probably been a while since you used strings, and we will be using them again in this unit, try using a few of the methods listed in the output. For example, add the following code and examine the output to remind yourself of what each of the following methods does.
字符串几乎用于您将编写的每个程序中。由于您可能有一段时间没有使用字符串了,而且我们将在本单元中再次使用它们,请尝试使用输出中列出的一些方法。例如,添加以下代码并检查输出,以提醒自己以下每个方法的作用。
print(some_string.__sizeof__())
print(some_string.startswith(“I”))
Understanding strings is assumed knowledge in this unit. If you are struggling using string methods it is advisable to review the content on strings from Programming 1.
理解字符串是本单元的假设知识。如果您在使用字符串方法方面有困难,建议您复习编程1中关于字符串的内容。
User-Defined Classes
If Python’s built-in classes or modules do not offer the specific functionalities you need, you can create your own classes to implement these behaviours. Classes make it easier to model real-world scenarios. Complex entities and interactions in real-world systems can be effectively represented and managed through custom classes. For example, suppose you’re developing a software system for a company like Netflix. In that case, you might create classes like Actor and Movie where each class encapsulates the data and behaviours relevant to these entities. This would make the code more organised and understandable and facilitate future enhancements and maintenance.
如果 Python 的内置类或模块不提供您需要的特定功能,您可以创建自己的类来实现这些行为。类使建模真实场景变得更加容易。现实世界系统中的复杂实体和交互可以通过自定义类有效地表示和管理。例如,假设您正在为 Netflix 这样的公司开发一个软件系统。在这种情况下,您可能会创建像 Actor 和 Movie 这样的类,每个类封装与这些实体相关的数据和行为。这将使代码更有条理、更易于理解,并促进未来的增强和维护。
class Actor:
pass
print(Actor)
helen = Actor()
print(type(helen))
helen.first_name = "Helen"
helen.last_name = "Mirren"
print(helen.first_name, helen.last_name)
Let’s create a class to collect information about actors.
让我们创建一个类来收集关于演员的信息。
In your IDE, create a new Python file and add the following code.
在您的 IDE 中,创建一个新的 Python 文件并添加以下代码。
2. pass
3.
4. print(Actor)
Naming classes
Before we continue working with the actor class, we need to talk about how to name classes according to Python’s naming conventions.
在继续使用 actor 类之前,我们需要讨论如何根据 Python 的命名约定来命名类。
The convention for naming classes in Python is to use UpperCamelCase. UpperCamelCase is a naming convention in programming where each word starts with a capital letter, and there are no spaces or punctuation. Here are some characteristics and examples of UpperCamelCase:
Python 中命名类的约定是使用 UpperCamelCase。UpperCamelCase 是一种编程命名约定,其中每个单词以大写字母开头,没有空格或标点符号。以下是 UpperCamelCase 的一些特点和示例:
- Capitalisation: Each word, including the first, starts with a capital letter. / 大写:每个单词(包括第一个)都以大写字母开头。
- No Spaces or Underscores: Words are written without spaces or underscores between them. / 无空格或下划线:单词之间没有空格或下划线。
- Readability: Despite the lack of spaces, the capitalisation of each word helps distinguish where one word ends and another begins. / 可读性:尽管没有空格,但每个单词的大写有助于区分一个单词的结束和另一个单词的开始。
Examples: MyClass, UserProfile, ElectricCar.
示例:MyClass, UserProfile, ElectricCar。
Not following this convention will not cause an error message, but it is not considered to be correct.
不遵循此约定不会导致错误消息,但被认为是不正确的。
Creating an Object
Remember, classes are a blueprint for objects. To use a class, you need to create an object. We will create an object representing the actress, Helen Mirren.
请记住,类是对象的蓝图。要使用类,您需要创建一个对象。我们将创建一个代表女演员 Helen Mirren 的对象。
class Actor:
pass
helen = Actor()
print(type(helen))
Update the Actor class as shown below.
如下所示更新 Actor 类。
On line 4, helen is a variable that is assigned an instance of the Actor class. The Actor() syntax creates a new instance of the Actor class. This is a standard way to create objects in Python.
在第4行,helen 是一个被赋值为 Actor 类实例的变量。Actor() 语法创建了一个新的 Actor 类实例。这是在 Python 中创建对象的标准方式。
Line 5 prints the type of the variable helen. The output indicates that helen is an instance of the Actor class defined in the main module.
第5行打印变量 helen 的类型。输出表明 helen 是在主模块中定义的 Actor 类的一个实例。
Adding Attributes
At the moment, the Actor class does not do anything. The point of having a class is to store data and define the behaviours that can modify the data. The Actor class should contain things like the name of the actor, notable films, awards they have won, etc. These pieces of data related to a class are called attributes or instance variables. These terms refer to variables that belong to a class or an instance of a class and the data stored in them is referred to as the object state.
目前,Actor 类什么也不做。拥有类的目的是存储数据并定义可以修改数据的行为。Actor 类应该包含演员的姓名、著名电影、获得的奖项等。这些与类相关的数据称为属性或实例变量。这些术语指的是属于类或类实例的变量,其中存储的数据称为对象状态。
Adding attributes to a Python class can be done in several ways. The example below demonstrates how to add attributes dynamically.
向 Python 类添加属性可以通过多种方式完成。下面的示例演示了如何动态添加属性。
You access attributes by using dot notation. Dot notation is a syntax for accessing an object’s methods or attributes using the object name followed by a dot, then the attribute name. For example, object_name.attribute_name.
您可以使用点符号访问属性。点符号是一种使用对象名称后跟点号再跟属性名称来访问对象方法或属性的语法。例如,object_name.attribute_name。
class Actor:
pass
helen = Actor()
helen.first_name = "Helen"
helen.last_name = "Mirren"
print(helen.first_name, helen.last_name)
Update the Actor class as shown below.
如下所示更新 Actor 类。
Line 7 prints the values of the first_name and last_name attributes of the helen instance. The output of this line will be:
第7行打印 helen 实例的 first_name 和 last_name 属性的值。该行的输出将是:
Activity 4: Adding Attributes
The Actor class requires some extra attributes. Add attributes for the following:
Actor 类需要一些额外的属性。添加以下属性:
- total_films with a value of 80 / total_films 值为 80
- notable_films with the value of [“The Queen”, “The Madness of King George”, “Gosford Park”] / notable_films 值为 [“The Queen”, “The Madness of King George”, “Gosford Park”]
Constructors
class Actor:
"""Define the actor class"""
def __init__(self, first_name, last_name, birthday, total_films, oscar_nominations, oscar_wins):
self.first_name = first_name
self.last_name = last_name
self.birthday = birthday
self.total_films = total_films
self.oscar_nominations = oscar_nominations
self.oscar_wins = oscar_wins
helen = Actor("Helen", "Mirren", "July 26", 80, 4, 1)
tom = Actor("Tom", "Hanks", "July 9", 76, 5, 2)
print(helen.first_name, helen.last_name)
print(tom.first_name, tom.last_name)
In Python, the constructor is coded as __init__. The double underscores before and after init are required. Constructors use the same syntax for the constructor as the functions you wrote in Programming 1. Make sure you indent the constructor four spaces since it is a part of the class.
在 Python 中,构造函数被编码为 __init__。init 前后的双下划线是必需的。构造函数使用的语法与您在编程1中编写的函数相同。确保构造函数缩进四个空格,因为它是类的一部分。
The constructor must have self as a parameter. Within the constructor, several attributes are initialised with specific values. The self keyword is used to refer to the current instance of the class, and it is through self that attributes are defined and accessed.
构造函数必须将 self 作为参数。在构造函数内部,多个属性被初始化为特定值。self 关键字用于引用类的当前实例,通过 self 定义和访问属性。
When Actor() is called, the __init__ method is automatically executed, initialising the attributes of the instance.
当调用 Actor() 时,__init__ 方法会自动执行,初始化实例的属性。
Dunder methods
You may wonder why the constructor has double underscores before and after init.
您可能想知道为什么构造函数在 init 前后有双下划线。
In Python, a “dunder method” (short for “double underscore method”) refers to special methods that have names beginning and ending with double underscores (__). Python uses dunder methods to provide special functionality to objects. They are not typically called directly by the programmer but rather by Python internally.
在 Python 中,”dunder method”(”double underscore method” 的缩写)指的是名称以双下划线(__)开头和结尾的特殊方法。Python 使用 dunder 方法为对象提供特殊功能。它们通常不是由程序员直接调用,而是由 Python 内部调用。
A constructor is an example of a dunder method. You never have to call a constructor. When you instantiate the object, Python calls automatically.
构造函数是 dunder 方法的一个示例。您永远不需要调用构造函数。当您实例化对象时,Python 会自动调用它。
Default Parameters
Like functions, classes can use default parameters in a constructor. Most actors have yet to be nominated for an Oscar, and even fewer win one. It is reasonable to assume that the “default” actor has 0 Oscar nominations and 0 wins. Therefore, these two parameters can default to 0 unless explicitly stated.
与函数一样,类可以在构造函数中使用默认参数。大多数演员还没有获得奥斯卡提名,获得奥斯卡奖的更少。可以合理地假设”默认”演员有0次奥斯卡提名和0次获奖。因此,除非明确说明,否则这两个参数可以默认为0。
class Actor:
"""Define the actor class"""
def __init__(self, first_name, last_name, birthday, total_films, oscar_nominations=0, oscar_wins=0):
self.first_name = first_name
self.last_name = last_name
self.birthday = birthday
self.total_films = total_films
self.oscar_nominations = oscar_nominations
self.oscar_wins = oscar_wins
helen = Actor("Helen", "Mirren", "July 26", 80, 4, 1)
dwayne = Actor("Dwayne", "Johnson", "July 9", 34)
print(f'{helen.first_name} won {helen.oscar_wins} oscar(s).')
print(f'{dwayne.first_name} won {dwayne.oscar_wins} oscar(s).')
Notice how the last two parameters, oscar_nominations and oscar_wins, have default values of 0. This means that if values for these parameters are not provided when an instance is created, they will default to 0.
注意最后两个参数 oscar_nominations 和 oscar_wins 的默认值为0。这意味着如果在创建实例时没有为这些参数提供值,它们将默认为0。
Class Attributes
As we have seen the __init__ method creates attributes. The more technical term for these attributes is instance attributes or object attributes as they can be different from object to object. That’s why the objects helen and dwayne can have different values stored in each attribute.
正如我们所看到的,__init__ 方法创建属性。这些属性的更技术性术语是实例属性或对象属性,因为它们可以因对象而异。这就是为什么 helen 和 dwayne 对象可以在每个属性中存储不同的值。
class Actor:
"""Define the actor class"""
union = "Screen Actors Guild"
def __init__(self, first_name, last_name, birthday, total_films, oscar_nominations=0, oscar_wins=0):
self.first_name = first_name
self.last_name = last_name
self.birthday = birthday
self.total_films = total_films
self.oscar_nominations = oscar_nominations
self.oscar_wins = oscar_wins
helen = Actor("Helen", "Mirren", "July 26", 80, 4, 1)
dwayne = Actor("Dwayne", "Johnson", "July 9", 34)
print("{} {} is a member of the {}.".format(helen.first_name, helen.last_name, helen.union))
print("{} {} is a member of the {}.".format(dwayne.first_name, dwayne.last_name, dwayne.union))
Python also allows you to create class attributes. Class attributes are variables defined directly inside a class and outside any method. These attributes are shared across all instances of the class. This means that if you change the value of a class attribute, it changes for all instances of the class. Class attributes are often used to define properties or behaviours that should be the same for each instance of the class.
Python 还允许您创建类属性。类属性是直接在类内部、任何方法外部定义的变量。这些属性在类的所有实例之间共享。这意味着如果您更改类属性的值,它将更改类的所有实例。类属性通常用于定义对于类的每个实例应该相同的属性或行为。
Mutability
Objects are mutable, which means that objects (specifically their attributes) can change value. Think of a video game. The main character in the game is constantly changing. It could be their position on the screen, their score, their health, the items in their inventory, etc.
对象是可变的,这意味着对象(特别是它们的属性)可以改变值。想想一个视频游戏。游戏中的主角在不断变化。可能是他们在屏幕上的位置、他们的分数、他们的生命值、他们库存中的物品等。
class Player:
"""Simple player class"""
def __init__(self, health=100, score=0, level=1):
self.health = health
self.score = score
self.level = level
player1 = Player()
print(f"This player has {player1.health} health, a score of {player1.score}, and is on level {player1.level}.")
player1.health -= 10
player1.score += 25
player1.level += 1
print(f"This player has {player1.health} health, a score of {player1.score}, and is on level {player1.level}.")
Methods and Objects
A class defines the structure and behaviour of objects. As you have seen, attributes are variables that belong to a class. They represent the state or data of the objects created from the class. Methods are functions that belong to a class. They define the behaviour of the objects.
类定义了对象的结构和行为。正如您所看到的,属性是属于类的变量。它们表示从类创建的对象的 state 或数据。方法是属于类的函数。它们定义了对象的行为。
class Player:
"""Simple player class"""
def __init__(self, health=100, score=0, level=1):
self.health = health
self.score = score
self.level = level
def print_player(self):
if self.health <= 0:
print(f"This player is dead. They died on level {self.level} with a score of {self.score}.")
else:
print(f"This player has {self.health} health, a score of {self.score}, and is on level {self.level}.")
def change_health(self, amount):
self.health += amount
def change_level(self):
self.level += 1
mario = Player()
mario.print_player()
mario.change_health(-10)
mario.change_level()
mario.print_player()
As you are familiar with functions from Programming 1, in the previous section, we used external functions to modify an object's state. While it works, there are better ways to do this. Instead of functions, methods should be used to modify an object.
正如您熟悉编程1中的函数,在上一节中,我们使用外部函数来修改对象的状态。虽然它有效,但有更好的方法。应该使用方法来修改对象,而不是函数。
We briefly introduced methods in programming 1. A method in Python is similar to a function but is associated with an object or class. Methods are defined within a class and are meant to operate on the attributes contained within that class (the object's state).
我们在编程1中简要介绍了方法。Python 中的方法类似于函数,但与对象或类相关联。方法在类内部定义,用于操作该类中包含的属性(对象的状态)。
Lists, Methods, and Objects
class Movie:
"""Define the movie class"""
def __init__(self, title, release_year):
self.title = title
self.release_year = release_year
class Actor:
"""Define the actor class"""
def __init__(self, first_name, last_name, birthday, total_films, oscar_nominations, oscar_wins, movies):
self.first_name = first_name
self.last_name = last_name
self.birthday = birthday
self.total_films = total_films
self.oscar_nominations = oscar_nominations
self.oscar_wins = oscar_wins
self.movies = movies
the_queen = Movie("The Queen", 2006)
another_movie = Movie("Another Movie", 2010)
helen = Actor("Helen", "Mirren", "July 26", 80, 4, 1, [the_queen, another_movie])
The key modification in the provided code is changing the movie attribute in the Actor class to movies, which is now expected to be a list of Movie objects instead of a single Movie object.
提供的代码中的关键修改是将 Actor 类中的 movie 属性更改为 movies,现在它应该是 Movie 对象的列表,而不是单个 Movie 对象。
Meal Class Example
class Meal:
"""Class to represent a meal"""
def __init__(self):
self.drinks = []
self.appetizers = []
self.main_course = []
self.desserts = []
def add_drink(self, d):
self.drinks.append(d)
def add_appetizer(self, a):
self.appetizers.append(a)
dinner = Meal()
dinner.add_drink("water")
print(dinner.drinks)
dinner.add_appetizer("bruschetta")
print(dinner.appetizers)
Notice how the constructor initialises four instance attributes: drinks, appetisers, main_course, and desserts. Each attribute is initialised to an empty list ([]). These lists are intended to hold the items that make up the different parts of a meal.
注意构造函数如何初始化四个实例属性:drinks、appetizers、main_course 和 desserts。每个属性被初始化为一个空列表([])。这些列表用于保存组成一餐不同部分的项目。
Activity 12: Create methods
Create the following methods in the Meal class:
在 Meal 类中创建以下方法:
- add_course - accepts a string representing a course and adds it to the meal. / add_course - 接受表示一道菜的字符串并将其添加到 meal 中。
- add_dessert - accepts a string that represents a dessert and adds it to the meal. / add_dessert - 接受表示甜点的字符串并将其添加到 meal 中。
class Meal:
"""Class to represent a meal"""
def __init__(self):
self.drinks = []
self.appetizers = []
self.main_course = []
self.desserts = []
def add_drink(self, d):
self.drinks.append(d)
def add_appetizer(self, a):
self.appetizers.append(a)
def add_course(self, c):
self.main_course.append(c)
def add_dessert(self, d):
self.desserts.append(d)
dinner = Meal()
dinner.add_drink("water")
dinner.add_appetizer("bruschetta")
dinner.add_course("steak")
dinner.add_dessert("cake")
print("Drinks:", dinner.drinks)
print("Appetizers:", dinner.appetizers)
print("Main Course:", dinner.main_course)
print("Desserts:", dinner.desserts)
Summary
This module introduced fundamental concepts of object-oriented programming (OOP) in Python, including classes, objects, attributes, constructors, and methods. These concepts are crucial for developing structured, efficient, and scalable Python applications. In the next module we will continue with classes and objects and cover more advanced topics including encapsulation, inheritance, and polymorphism.
本模块介绍了 Python 中面向对象编程(OOP)的基本概念,包括类、对象、属性、构造函数和方法。这些概念对于开发结构化、高效和可扩展的 Python 应用程序至关重要。在下一模块中,我们将继续学习类和对象,并涵盖更高级的主题,包括封装、继承和多态。
Final Activity: Test your understanding
Attend the Module 1 Live Coding session (Monday, week 1 at 1 pm NSW time) via Collaborate Ultra or watch the recording and follow along with the demonstration.
通过 Collaborate Ultra 参加模块1的现场编程会议(第1周周一 NSW 时间下午1点)或观看录像并跟随演示。
📎 car_hire.py - 3.723 KB
📎 weather_data.py - 3.077 KB
JavaScript 闭包核心
闭包是指函数能记住并访问它的词法作用域。
🔒 闭包应用场景:
• 模块化封装私有变量
• 防抖节流函数
• 循环中的事件绑定