当前位置: 首页 > news >正文

Chapter 15: Object-Oriented Programming | Python for Everybody 讲义笔记_En

文章目录

  • Python for Everybody
    • 课程简介
    • Object-oriented programming
      • Managing larger programs
      • Getting started
      • Using objects
      • Starting with programs
      • Subdividing a problem
      • Our first Python object
      • Classes as types
      • Object lifecycle
      • Multiple instances
      • Inheritance
      • Summary
      • Glossary


Python for Everybody

Exploring Data Using Python 3
Dr. Charles R. Severance


课程简介

Python for Everybody 零基础程序设计(Python 入门)

  • This course aims to teach everyone the basics of programming computers using Python. 本课程旨在向所有人传授使用 Python 进行计算机编程的基础知识。
  • We cover the basics of how one constructs a program from a series of simple instructions in Python. 我们介绍了如何通过 Python 中的一系列简单指令构建程序的基础知识。
  • The course has no pre-requisites and avoids all but the simplest mathematics. Anyone with moderate computer experience should be able to master the materials in this course. 该课程没有任何先决条件,除了最简单的数学之外,避免了所有内容。任何具有中等计算机经验的人都应该能够掌握本课程中的材料。
  • This course will cover Chapters 1-5 of the textbook “Python for Everybody”. Once a student completes this course, they will be ready to take more advanced programming courses. 本课程将涵盖《Python for Everyday》教科书的第 1-5 章。学生完成本课程后,他们将准备好学习更高级的编程课程。
  • This course covers Python 3.

在这里插入图片描述

coursera

Python for Everybody 零基础程序设计(Python 入门)

Charles Russell Severance
Clinical Professor

在这里插入图片描述

个人主页
Twitter

在这里插入图片描述

University of Michigan


课程资源

coursera原版课程视频
coursera原版视频-中英文精校字幕-B站
Dr. Chuck官方翻录版视频-机器翻译字幕-B站

PY4E-课程配套练习
Dr. Chuck Online - 系列课程开源官网



Object-oriented programming

Python Objects.
We do a quick look at how Python supports the Object-Oriented programming pattern.


Managing larger programs

At the beginning of this book, we came up with four basic programming patterns which we use to construct programs:

  • Sequential code
  • Conditional code (if statements)
  • Repetitive code (loops)
  • Store and reuse (functions)

In later chapters, we explored simple variables as well as collection data structures like lists, tuples, and dictionaries.

As we build programs, we design data structures and write code to manipulate those data structures. There are many ways to write programs and by now, you probably have written some programs that are “not so elegant” and other programs that are “more elegant”. Even though your programs may be small, you are starting to see how there is a bit of art and aesthetic to writing code.

As programs get to be millions of lines long, it becomes increasingly important to write code that is easy to understand. If you are working on a million-line program, you can never keep the entire program in your mind at the same time. We need ways to break large programs into multiple smaller pieces so that we have less to look at when solving a problem, fix a bug, or add a new feature.

In a way, object oriented programming is a way to arrange your code so that you can zoom into 50 lines of the code and understand it while ignoring the other 999,950 lines of code for the moment.


Getting started

Like many aspects of programming, it is necessary to learn the concepts of object oriented programming before you can use them effectively. You should approach this chapter as a way to learn some terms and concepts and work through a few simple examples to lay a foundation for future learning.

The key outcome of this chapter is to have a basic understanding of how objects are constructed and how they function and most importantly how we make use of the capabilities of objects that are provided to us by Python and Python libraries.

Using objects

As it turns out, we have been using objects all along in this book. Python provides us with many built-in objects. Here is some simple code where the first few lines should feel very simple and natural to you.

stuff = list()
stuff.append('python')
stuff.append('chuck')
stuff.sort()
print (stuff[0])
print (stuff.__getitem__(0))
print (list.__getitem__(stuff,0))# Code: http://www.py4e.com/code3/party1.py

Instead of focusing on what these lines accomplish, let’s look at what is really happening from the point of view of object-oriented programming. Don’t worry if the following paragraphs don’t make any sense the first time you read them because we have not yet defined all of these terms.

The first line constructs an object of type list, the second and third lines call the append() method, the fourth line calls the sort() method, and the fifth line retrieves the item at position 0.

The sixth line calls the __getitem__() method in the stuff list with a parameter of zero.

print (stuff.__getitem__(0))

The seventh line is an even more verbose way of retrieving the 0th item in the list.

print (list.__getitem__(stuff,0))

In this code, we call the __getitem__ method in the list class and pass the list and the item we want retrieved from the list as parameters.

The last three lines of the program are equivalent, but it is more convenient to simply use the square bracket syntax to look up an item at a particular position in a list.

We can take a look at the capabilities of an object by looking at the output of the dir() function:

>>> stuff = list()
>>> dir(stuff)
['__add__', '__class__', '__contains__', '__delattr__',
'__delitem__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getitem__',
'__gt__', '__hash__', '__iadd__', '__imul__', '__init__',
'__iter__', '__le__', '__len__', '__lt__', '__mul__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__reversed__', '__rmul__', '__setattr__',
'__setitem__', '__sizeof__', '__str__', '__subclasshook__',
'append', 'clear', 'copy', 'count', 'extend', 'index',
'insert', 'pop', 'remove', 'reverse', 'sort']
>>>

The rest of this chapter will define all of the above terms so make sure to come back after you finish the chapter and re-read the above paragraphs to check your understanding.


Starting with programs

A program in its most basic form takes some input, does some processing, and produces some output. Our elevator conversion program demonstrates a very short but complete program showing all three of these steps.

usf = input('Enter the US Floor Number: ')
wf = int(usf) - 1
print('Non-US Floor Number is',wf)# Code: http://www.py4e.com/code3/elev.py

If we think a bit more about this program, there is the “outside world” and the program. The input and output aspects are where the program interacts with the outside world. Within the program we have code and data to accomplish the task the program is designed to solve.


在这里插入图片描述

A Program


One way to think about object-oriented programming is that it separates our program into multiple “zones.” Each zone contains some code and data (like a program) and has well defined interactions with the outside world and the other zones within the program.

If we look back at the link extraction application where we used the BeautifulSoup library, we can see a program that is constructed by connecting different objects together to accomplish a task:

# To run this, download the BeautifulSoup zip file
# http://www.py4e.com/code3/bs4.zip
# and unzip it in the same directory as this fileimport urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONEurl = input('Enter - ')
html = urllib.request.urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, 'html.parser')# Retrieve all of the anchor tags
tags = soup('a')
for tag in tags:print(tag.get('href', None))# Code: http://www.py4e.com/code3/urllinks.py

We read the URL into a string and then pass that into urllib to retrieve the data from the web. The urllib library uses the socket library to make the actual network connection to retrieve the data. We take the string that urllib returns and hand it to BeautifulSoup for parsing. BeautifulSoup makes use of the object html.parser1 and returns an object. We call the tags() method on the returned object that returns a dictionary of tag objects. We loop through the tags and call the get() method for each tag to print out the href attribute.

We can draw a picture of this program and how the objects work together.


在这里插入图片描述
A Program as Network of Objects


The key here is not to understand perfectly how this program works but to see how we build a network of interacting objects and orchestrate the movement of information between the objects to create a program. It is also important to note that when you looked at that program several chapters back, you could fully understand what was going on in the program without even realizing that the program was “orchestrating the movement of data between objects.” It was just lines of code that got the job done.


Subdividing a problem

One of the advantages of the object-oriented approach is that it can hide complexity. For example, while we need to know how to use the urllib and BeautifulSoup code, we do not need to know how those libraries work internally. This allows us to focus on the part of the problem we need to solve and ignore the other parts of the program.


在这里插入图片描述
Ignoring Detail When Using an Object


This ability to focus exclusively on the part of a program that we care about and ignore the rest is also helpful to the developers of the objects that we use. For example, the programmers developing BeautifulSoup do not need to know or care about how we retrieve our HTML page, what parts we want to read, or what we plan to do with the data we extract from the web page.


在这里插入图片描述
Ignoring Detail When Building an Object



Our first Python object

At a basic level, an object is simply some code plus data structures that are smaller than a whole program. Defining a function allows us to store a bit of code and give it a name and then later invoke that code using the name of the function.

An object can contain a number of functions (which we call methods) as well as data that is used by those functions. We call data items that are part of the object attributes.

We use the class keyword to define the data and code that will make up each of the objects. The class keyword includes the name of the class and begins an indented block of code where we include the attributes (data) and methods (code).

class PartyAnimal:x = 0def party(self) :self.x = self.x + 1print("So far",self.x)an = PartyAnimal()
an.party()
an.party()
an.party()
PartyAnimal.party(an)# Code: http://www.py4e.com/code3/party2.py

Each method looks like a function, starting with the def keyword and consisting of an indented block of code. This object has one attribute (x) and one method (party). The methods have a special first parameter that we name by convention self.

Just as the def keyword does not cause function code to be executed, the class keyword does not create an object. Instead, the class keyword defines a template indicating what data and code will be contained in each object of type PartyAnimal. The class is like a cookie cutter and the objects created using the class are the cookies2. You don’t put frosting on the cookie cutter; you put frosting on the cookies, and you can put different frosting on each cookie.


在这里插入图片描述
A Class and Two Objects


If we continue through this sample program, we see the first executable line of code:

an = PartyAnimal()

This is where we instruct Python to construct (i.e., create) an object or instance of the class PartyAnimal. It looks like a function call to the class itself. Python constructs the object with the right data and methods and returns the object which is then assigned to the variable an. In a way this is quite similar to the following line which we have been using all along:

counts = dict()

Here we instruct Python to construct an object using the dict template (already present in Python), return the instance of dictionary, and assign it to the variable counts.

When the PartyAnimal class is used to construct an object, the variable an is used to point to that object. We use an to access the code and data for that particular instance of the PartyAnimal class.

Each Partyanimal object/instance contains within it a variable x and a method/function named party. We call the party method in this line:

an.party()

When the party method is called, the first parameter (which we call by convention self) points to the particular instance of the PartyAnimal object that party is called from. Within the party method, we see the line:

self.x = self.x + 1

This syntax using the dot operator is saying ‘the x within self.’ Each time party() is called, the internal x value is incremented by 1 and the value is printed out.

The following line is another way to call the party method within the an object:

PartyAnimal.party(an)

In this variation, we access the code from within the class and explicitly pass the object pointer an as the first parameter (i.e., self within the method). You can think of an.party() as shorthand for the above line.

When the program executes, it produces the following output:

So far 1
So far 2
So far 3
So far 4

The object is constructed, and the party method is called four times, both incrementing and printing the value for x within the an object.


Classes as types

As we have seen, in Python all variables have a type. We can use the built-in dir function to examine the capabilities of a variable. We can also use type and dir with the classes that we create.

class PartyAnimal:x = 0def party(self) :self.x = self.x + 1print("So far",self.x)an = PartyAnimal()
print ("Type", type(an))
print ("Dir ", dir(an))
print ("Type", type(an.x))
print ("Type", type(an.party))# Code: http://www.py4e.com/code3/party3.py

When this program executes, it produces the following output:

Type <class '__main__.PartyAnimal'>
Dir  ['__class__', '__delattr__', ...
'__sizeof__', '__str__', '__subclasshook__',
'__weakref__', 'party', 'x']
Type <class 'int'>
Type <class 'method'>

You can see that using the class keyword, we have created a new type. From the dir output, you can see both the x integer attribute and the party method are available in the object.


Object lifecycle

In the previous examples, we define a class (template), use that class to create an instance of that class (object), and then use the instance. When the program finishes, all of the variables are discarded. Usually, we don’t think much about the creation and destruction of variables, but often as our objects become more complex, we need to take some action within the object to set things up as the object is constructed and possibly clean things up as the object is discarded.

If we want our object to be aware of these moments of construction and destruction, we add specially named methods to our object:

class PartyAnimal:x = 0def __init__(self):print('I am constructed')def party(self) :self.x = self.x + 1print('So far',self.x)def __del__(self):print('I am destructed', self.x)an = PartyAnimal()
an.party()
an.party()
an = 42
print('an contains',an)# Code: http://www.py4e.com/code3/party4.py

When this program executes, it produces the following output:

I am constructed
So far 1
So far 2
I am destructed 2
an contains 42

As Python constructs our object, it calls our __init__ method to give us a chance to set up some default or initial values for the object. When Python encounters the line:

an = 42

It actually “throws our object away” so it can reuse the an variable to store the value 42. Just at the moment when our an object is being “destroyed” our destructor code (__del__) is called. We cannot stop our variable from being destroyed, but we can do any necessary cleanup right before our object no longer exists.

When developing objects, it is quite common to add a constructor to an object to set up initial values for the object. It is relatively rare to need a destructor for an object.


Multiple instances

So far, we have defined a class, constructed a single object, used that object, and then thrown the object away. However, the real power in object-oriented programming happens when we construct multiple instances of our class.

When we construct multiple objects from our class, we might want to set up different initial values for each of the objects. We can pass data to the constructors to give each object a different initial value:

class PartyAnimal:x = 0name = ''def __init__(self, nam):self.name = namprint(self.name,'constructed')def party(self) :self.x = self.x + 1print(self.name,'party count',self.x)s = PartyAnimal('Sally')
j = PartyAnimal('Jim')s.party()
j.party()
s.party()# Code: http://www.py4e.com/code3/party5.py

The constructor has both a self parameter that points to the object instance and additional parameters that are passed into the constructor as the object is constructed:

s = PartyAnimal('Sally')

Within the constructor, the second line copies the parameter (nam) that is passed into the name attribute within the object instance.

self.name = nam

The output of the program shows that each of the objects (s and j) contain their own independent copies of x and nam:

Sally constructed
Jim constructed
Sally party count 1
Jim party count 1
Sally party count 2

Inheritance

Another powerful feature of object-oriented programming is the ability to create a new class by extending an existing class. When extending a class, we call the original class the parent class and the new class the child class.

For this example, we move our PartyAnimal class into its own file. Then, we can ‘import’ the PartyAnimal class in a new file and extend it, as follows:

from party import PartyAnimalclass CricketFan(PartyAnimal):points = 0def six(self):self.points = self.points + 6self.party()print(self.name,"points",self.points)s = PartyAnimal("Sally")
s.party()
j = CricketFan("Jim")
j.party()
j.six()
print(dir(j))# Code: http://www.py4e.com/code3/party6.py

When we define the CricketFan class, we indicate that we are extending the PartyAnimal class. This means that all of the variables (x) and methods (party) from the PartyAnimal class are inherited by the CricketFan class. For example, within the six method in the CricketFan class, we call the party method from the PartyAnimal class.

As the program executes, we create s and j as independent instances of PartyAnimal and CricketFan. The j object has additional capabilities beyond the s object.

Sally constructed
Sally party count 1
Jim constructed
Jim party count 1
Jim party count 2
Jim points 6
['__class__', '__delattr__', ... '__weakref__',
'name', 'party', 'points', 'six', 'x']

In the dir output for the j object (instance of the CricketFan class), we see that it has the attributes and methods of the parent class, as well as the attributes and methods that were added when the class was extended to create the CricketFan class.


Summary

This is a very quick introduction to object-oriented programming that focuses mainly on terminology and the syntax of defining and using objects. Let’s quickly review the code that we looked at in the beginning of the chapter. At this point you should fully understand what is going on.

stuff = list()
stuff.append('python')
stuff.append('chuck')
stuff.sort()
print (stuff[0])
print (stuff.__getitem__(0))
print (list.__getitem__(stuff,0))# Code: http://www.py4e.com/code3/party1.py

The first line constructs a list object. When Python creates the list object, it calls the constructor method (named __init__) to set up the internal data attributes that will be used to store the list data. We have not passed any parameters to the constructor. When the constructor returns, we use the variable stuff to point to the returned instance of the list class.

The second and third lines call the append method with one parameter to add a new item at the end of the list by updating the attributes within stuff. Then in the fourth line, we call the sort method with no parameters to sort the data within the stuff object.

We then print out the first item in the list using the square brackets which are a shortcut to calling the __getitem__ method within the stuff. This is equivalent to calling the __getitem__ method in the list class and passing the stuff` object as the first parameter and the position we are looking for as the second parameter.

At the end of the program, the stuff object is discarded but not before calling the destructor (named __del__) so that the object can clean up any loose ends as necessary.

Those are the basics of object-oriented programming. There are many additional details as to how to best use object-oriented approaches when developing large applications and libraries that are beyond the scope of this chapter.3


Glossary

attribute
A variable that is part of a class.
class
A template that can be used to construct an object. Defines the attributes and methods that will make up the object.
child class
A new class created when a parent class is extended. The child class inherits all of the attributes and methods of the parent class.
constructor
An optional specially named method (__init__) that is called at the moment when a class is being used to construct an object. Usually this is used to set up initial values for the object.
destructor
An optional specially named method (__del__) that is called at the moment just before an object is destroyed. Destructors are rarely used.
inheritance
When we create a new class (child) by extending an existing class (parent). The child class has all the attributes and methods of the parent class plus additional attributes and methods defined by the child class.
method
A function that is contained within a class and the objects that are constructed from the class. Some object-oriented patterns use ‘message’ instead of ‘method’ to describe this concept.
object
A constructed instance of a class. An object contains all of the attributes and methods that were defined by the class. Some object-oriented documentation uses the term ‘instance’ interchangeably with ‘object’.
parent class
The class which is being extended to create a new child class. The parent class contributes all of its methods and attributes to the new child class.


  1. https://docs.python.org/3/library/html.parser.html ↩︎

  2. Cookie image copyright CC-BY https://www.flickr.com/photos/dinnerseries/23570475099↩︎ ↩︎

  3. If you are curious about where the list class is defined, take a look at (hopefully the URL won’t change) https://github.com/python/cpython/blob/master/Objects/listobject.c - the list class is written in a language called “C”. If you take a look at that source code and find it curious you might want to explore a few Computer Science courses.↩︎ ↩︎

相关文章:

Chapter 15: Object-Oriented Programming | Python for Everybody 讲义笔记_En

文章目录 Python for Everybody课程简介Object-oriented programmingManaging larger programsGetting startedUsing objectsStarting with programsSubdividing a problemOur first Python objectClasses as typesObject lifecycleMultiple instancesInheritanceSummaryGlossa…...

模板编程-成员特化

成员特化:类模板特化除了可以对整个类进行特化外,可以只针对某部分成员函数进行特化 全类特化和成员特化都属于全局特化 #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <cstring>template<typename T> class CMath { public:CMath(const…...

信安通用基础知识

文章目录 密码学经典误区PGP优良保密协议信安经典其它安全手段XSS与CSRF cross site request forgeryCSRF的利用逻辑CSRF示例CSRF防范检查Referer字段添加校验token XSS cross site scripting common weakness enumeration常见密码api误用&#xff08;摘自毕设参考文献&#xf…...

网上购物系统的设计与实现/在线商城/基于spring boot的电商平台/基于Java的商品销售系统

摘 要 本毕业设计的内容是设计并且实现一个基于Springboot的网上购物系统。它是在Windows下&#xff0c;以MYSQL为数据库开发平台&#xff0c;Tomcat网络信息服务作为应用服务器。网上购物系统的功能已基本实现&#xff0c;主要包括用户管理、数码分类管理、数码产品管理、服…...

uniapp项目-配置store文件夹

1.创建store.js 说明&#xff1a;创建一个新的 Vuex Store 实例&#xff0c;配置 Store 中的模块。 import Vue from vue; import Vuex from vuex; // 导入两个 Vuex 模块&#xff1a;moduleCart 和 moduleUser import moduleCart from /store/cart.js; import moduleUser fr…...

element表格多选实现

表格实现多选 实现表格多选很简单&#xff0c;只需要在表格里加上一列即可&#xff0c;加完之后就会在表格里出现一列白色的四方块按钮&#xff0c;可以多选&#xff0c;也可以单选 <el-table-columntype"selection"width"55"align"center"&…...

宠物智能自动喂食器方案设计

据相关数据表明&#xff0c;2019年全国城镇宠物犬猫数量达到9915万只&#xff0c;增幅达到8.4%&#xff0c;消费市场规模达2024亿元&#xff0c;比2018年增长18.5%&#xff0c;整体呈现持续大幅增长的态势。而养宠人群的主力&#xff0c;为25岁至38岁年轻人&#xff0c;都市白领…...

学习笔记230818---对于promise失败状态处理的重要性

问题描述&#xff1a; 在项目中经常会出现如上的问题&#xff0c;这是因为&#xff0c;用promise封装的接口或第三方组件方法&#xff0c;如果只对成功的状态做处理&#xff0c;就会造成页面出错&#xff0c;报error。 解决方法 then()的末尾加上.catch(()>{})对失败的状态…...

【Redis】什么是缓存击穿,如何预防缓存击穿?

【Redis】什么是缓存击穿&#xff0c;如何预防缓存击穿&#xff1f; 缓存击穿是指一个 Key 非常热点&#xff0c;大并发集中对这一个点进行访问&#xff0c;当这个Key 在失效的瞬间&#xff0c;持续的大并发就会穿破缓存&#xff0c;直接请求数据库。缓存击穿和缓存雪崩的区别…...

Android 13.0 强制app横屏显示

1.概述 在13.0产品定制化开发中,对于处理屏幕旋转方向,首先有kernel底层处理,从底层驱动gsensor 中获取数据,从而判断屏幕方向的,然后事件上报后 最后由WMS就是WindowManagerService 来处理旋转的相关事件 2.强制app横屏显示的核心类 /framework/base/services/java/com…...

平方数之和(力扣)双指针 JAVA

给定一个非负整数 c &#xff0c;你要判断是否存在两个整数 a 和 b&#xff0c;使得 a&#xff3e;2 b&#xff3e;2 c 。 示例 1&#xff1a; 输入&#xff1a;c 5 输出&#xff1a;true 解释&#xff1a;1 * 1 2 * 2 5 示例 2&#xff1a; 输入&#xff1a;c 3 输出&am…...

深入浅出Pytorch函数——torch.nn.init.sparse_

分类目录&#xff1a;《深入浅出Pytorch函数》总目录 相关文章&#xff1a; 深入浅出Pytorch函数——torch.nn.init.calculate_gain 深入浅出Pytorch函数——torch.nn.init.uniform_ 深入浅出Pytorch函数——torch.nn.init.normal_ 深入浅出Pytorch函数——torch.nn.init.c…...

OpenCV实现BGR2BayerGB/BG格式的转换

1、说明 OpenCV没有提供从BGR生成Bayer格式的接口,需要自己写 OpenCV定义为4种格式,分别为: BGGR排列 -> RG格式 RGGB排列 -> BG格式 GRBG排列 -> GB格式 GBRG排列 -> GR格式 2、转换 void CUtils::BGR2BayerGB(const cv::Mat &matSrc, cv::Mat &matDst)…...

Gateway网关路由以及predicates用法(项目中使用场景)

1.Gatewaynacos整合微服务 服务注册在nacos上&#xff0c;通过Gateway路由网关配置统一路由访问 这里主要通过yml方式说明&#xff1a; route: config: #type:database nacos yml data-type: yml group: DEFAULT_GROUP data-id: jeecg-gateway-router 配置路由&#xff1a;…...

深入浅出Pytorch函数——torch.nn.init.constant_

分类目录&#xff1a;《深入浅出Pytorch函数》总目录 相关文章&#xff1a; 深入浅出Pytorch函数——torch.nn.init.calculate_gain 深入浅出Pytorch函数——torch.nn.init.uniform_ 深入浅出Pytorch函数——torch.nn.init.normal_ 深入浅出Pytorch函数——torch.nn.init.c…...

centos mysql8解决Access denied for user ‘root‘@‘localhost‘ (using password: YES)

环境 系统&#xff1a;CentOS Stream release 9 mysql版本&#xff1a;mysql Ver 8.0.34 for Linux on x86_64 问题 mysql登录提示 Access denied for user rootlocalhost (using password: YES)解决方法 编辑 /etc/my.cnf &#xff0c;在[mysqld] 部分最后添加一行 skip-…...

Docker实战:Docker常用命令

一、镜像相关 1.1、查看镜像 docker images1.2、拉取镜像 docker pull nginx1.3、保存镜像 docker save -o nginx.tar nginx:latest1.4、移除镜像 docker rmi -f nginx:latest1.5、导入镜像 docker load -i nginx.tar二、容器相关 2.1、启动容器 docker run --name red…...

基于51单片机直流电机转速数码管显示控制系统

一、系统方案 本文主要研究了利用MCS-51系列单片机控制PWM信号从而实现对直流电机转速进行控制的方法。本文中采用了三极管组成了PWM信号的驱动系统&#xff0c;并且对PWM信号的原理、产生方法以及如何通过软件编程对PWM信号占空比进行调节&#xff0c;从而控制其输入信号波形等…...

小程序商品如何指定打印机

有些商家&#xff0c;可能有多个仓库。不同的仓库&#xff0c;存放不同的商品。当客户下单时&#xff0c;小程序如何自动按照仓库拆分订单&#xff0c;如何让打印机自动打印对应仓库的订单呢&#xff1f;下面就来介绍一下吧。 1. 设置订单分发模式。进入管理员后台&#xff0c…...

LLaMA-7B微调记录

Alpaca&#xff08;https://github.com/tatsu-lab/stanford_alpaca&#xff09;在70亿参数的LLaMA-7B上进行微调&#xff0c;通过52k指令数据&#xff08;https://github.com/tatsu-lab/stanford_alpaca/blob/main/alpaca_data.json&#xff09;&#xff0c;在8个80GB A100上训…...

域名子目录发布问题(nginx、vue-element-admin、uni-app)

域名子目录发布问题&#xff08;nginx、vue-element-admin、uni-app&#xff09; 说明Vue-Element-Admin 代码打包nginx配置&#xff1a;uni-app打包 说明 使用一个域名下子目录进行打包&#xff1a; 比如&#xff1a; http://www.xxx.com/merchant 商户端代码 http://www.xx…...

【环境配置】Windows 10 安装 PyTorch 开发环境,以及验证 YOLOv8

Windows 10 安装 PyTorch 开发环境&#xff0c;以及验证 YOLOv8 最近搞了一台Windows机器&#xff0c;准备在上面安装深度学习的开发环境&#xff0c;并搭建部署YOLOv8做训练和测试使用&#xff1b; 环境&#xff1a; OS&#xff1a; Windows 10 显卡&#xff1a; RTX 3090 安…...

数学建模之“层次分析法”原理和代码详解

一、层次分析法简介 层次分析法&#xff08;Analytic Hierarchy Process&#xff0c;AHP&#xff09;是一种用于多准则决策分析和评估问题的定量方法&#xff0c;常用于数学建模中。它是由数学家托马斯赛蒂&#xff08;Thomas Saaty&#xff09;开发的。 层次分析法将复杂的决…...

使用IText导出复杂pdf

1、问题描述 需要将发票导出成pdf&#xff0c;要求每页都必须包含发票信息和表头行。 2、解决方法 使用IText工具实现PDF导出 IText8文档&#xff1a;Examples (itextpdf.com) 3、我的代码 引入Itext依赖&#xff0c;我这里用的是8.0.1版本 <dependency><groupId>…...

多线程并发服务器(TCP)

服务器 客户端 结果...

uni-app的Vue.js实现微信小程序的紧急事件登记页面功能

主要功能实现 完成发生时间选择功能&#xff0c;用户可以通过日期选择器选择事件发生的时间。实现事件类型选择功能&#xff0c;用户可以通过下拉选择框选择事件的类型。添加子养殖场编号输入框&#xff0c;用户可以输入与事件相关的子养殖场编号。完成事件描述输入功能&#…...

面试题 17.16.按摩师

​​题目来源&#xff1a; leetcode题目&#xff0c;网址&#xff1a;面试题 17.16. 按摩师 - 力扣&#xff08;LeetCode&#xff09; 解题思路&#xff1a; 动态规划&#xff0c;对于第 i 个预约&#xff0c;若接下&#xff0c;其最大值为不接上一个时的最大值与当前值之和&a…...

vscode里配置C#环境并运行.cs文件

vscode是一款跨平台、轻量级、开源的IDE, 支持C、C、Java、C#、R、Python、Go、Nodejs等多种语言的开发和调试。下面介绍在vscode里配置C#环境。这里以配置.Net SDK v5.0&#xff0c;语言版本为C#9.0&#xff0c;对应的开发平台为VS2019&#xff0c;作为案例说明。 1、下载vsc…...

uniapp配置添加阿里巴巴图标icon流程步骤

文章目录 下载复制文件到项目文件夹里项目配置目录结构显示图标 下载 阿里巴巴icon官网 https://www.iconfont.cn/ 复制文件到项目文件夹里 项目配置目录结构 显示图标...

大模型基础02:GPT家族与提示学习

大模型基础&#xff1a;GPT 家族与提示学习 从 GPT-1 到 GPT-3.5 GPT(Generative Pre-trained Transformer)是 Google 于2018年提出的一种基于 Transformer 的预训练语言模型。它标志着自然语言处理领域从 RNN 时代进入 Transformer 时代。GPT 的发展历史和技术特点如下: GP…...

算法基础课——基础算法(模板整理)

快速排序 快速排序 #include <iostream> #include <algorithm> using namespace std; int n; int s[100000]; int main() {cin>>n;for(int i0;i<n;i){cin>>s[i];}sort(s,sn);for(int i0;i<n;i){cout<<s[i]<<" ";}cout<…...

如何解决使用npm出现Cannot find module ‘XXX\node_modules\npm\bin\npm-cli.js’错误

遇到问题&#xff1a;用npm下载组件时出现Cannot find module ‘D&#xff1a;software\node_modules\npm\bin\npm-cli.js’ 问题&#xff0c;导致下载组件不能完成。 解决方法&#xff1a;下载缺少的npm文件即可解决放到指定node_modules目录下即可解决。 分析问题&#xff1…...

【华为认证数通高级证书实验-分享篇2】

实验拓扑 注&#xff1a;代码块为各交换机路由器中的配置命令 配置拓扑文件 实验要求 实现全网通 实验配置 SW3 [SW3]v b 10 20 [SW3]int e0/0/1 [SW3-Ethernet0/0/1]po link-t a [SW3-Ethernet0/0/1]po de v 10 [SW3-Ethernet0/0/1]int e0/0/2 [SW3-Ethernet0/0/2]po li…...

ui设计需要学编程吗难不难学习 优漫动游

ui设计需要学编程吗难不难学习&#xff0c;对于基础小白来说学习编程确实有一定难度&#xff0c;所以很想知道零基础学习ui设计需要学编程吗&#xff0c;需不需要写代码呢&#xff0c;这些问题小编来简单的分析分析解决零基础小白的一些困惑&#xff0c;希望对你有帮助。 ui…...

什么是线程优先级?Java中的线程优先级是如何定义和使用的?

线程优先级是指在多线程环境中&#xff0c;通过给线程分配不同的优先级来决定线程获取CPU时间片的顺序。优先级较高的线程会更有可能被调度执行&#xff0c;而优先级较低的线程可能会获得较少的CPU时间。 在Java中&#xff0c;线程优先级是通过整数表示的&#xff0c;范围从1到…...

无涯教程-TensorFlow - XOR实现

在本章中&#xff0c;无涯教程将学习使用TensorFlow的XOR实现&#xff0c;在TensorFlow中开始XOR实施之前&#xff0c;看一下XOR表值。这将帮助了解加密和解密过程。 A B A XOR B 0 0 0 0 1 1 1 0 1 1 1 0 XOR密码加密方法基本上用于加密&#xff0c;即通过生成与适当密钥匹配…...

计算机组成与设计 Patterson Hennessy 笔记(二)MIPS 指令集

计算机的语言&#xff1a;汇编指令集 也就是指令集。本书主要介绍 MIPS 指令集。 汇编指令 算数运算&#xff1a; add a,b,c # abc sub a,b,c # ab-cMIPS 汇编的注释是 # 号。 由于MIPS中寄存器大小32位&#xff0c;是基本访问单位&#xff0c;因此也被称为一个字 word。M…...

【设计模式】模板方法模式(Template Method Pattern)

23种设计模式之模板方法模式&#xff08;Template Method Pattern&#xff09; 基本概念 模板方法模式是一种行为型设计模式&#xff0c;它定义了一个算法骨架&#xff0c;将某些算法步骤的实现延迟到子类中。 这样可以使得算法的框架不被修改&#xff0c;但是具体的实现可以…...

【潮州饶平】联想 IBM x3850 x6 io主板故障 服务器维修

哈喽 最近比较忙也好久没有更新服务器维修案例了&#xff0c;这次分享一例潮州市饶平县某企业工厂一台IBM System x3850 x6服务器亮黄灯告警且无法正常开机的服务器故障问题。潮州饶平ibm服务器维修IO主板故障问题 故障如下图所示&#xff1a; 故障服务器型号&#xff1a;IBM 或…...

【AIGC】 国内版聊天GPT

国内版聊天GPT 引言一、国内平台二、简单体验2.1 提问2.2 角色扮演2.3 总结画图 引言 ChatGPT是OpenAI发开的聊天程序&#xff0c;功能强大&#xff0c;可快速获取信息&#xff0c;节省用户时间和精力&#xff0c;提供个性化的服务。目前国产ChatGPT&#xff0c;比如文心一言&a…...

如何在Vue中进行单元测试?什么是Vue的模块化开发?

1、如何在Vue中进行单元测试&#xff1f; 在Vue中进行单元测试可以提高代码的可维护性和可读性&#xff0c;同时也能够帮助开发者更快地找到代码中的问题和潜在的错误。下面是一些在Vue中进行单元测试的步骤&#xff1a; 安装单元测试工具 首先需要安装一个单元测试工具&…...

Matlab编程示例3:Matlab求二次积分的编程示例

1.在MATLAB中&#xff0c;可以使用符号计算工具箱(Symbolic Math Toolbox)中的int函数来求解二次积分。 2.下面是一个简单的MATLAB程序示例&#xff0c;演示二次函数f (x,y) x^2 y^2&#xff0c;在x∈[0 1]和y∈[0 1]的积分区间上&#xff0c;计算积分结果&#xff1a; syms…...

【Linux】线程同步和死锁

目录 死锁 什么是死锁 构成死锁的四个必要条件 如何避免死锁 线程同步 同步的引入 同步的方式 条件变量 条件变量的使用 整体代码 死锁 什么是死锁 死锁是指在一组进程中的各个进程均占有不会释放的资源&#xff0c;但因互相申请被其他进程所占用不会释放 的资源而处…...

Matplotlib数据可视化(二)

目录 1.rc参数设置 1.1 lines.linestype取值 1.2 lines.marker参数的取值 1.3 绘图中文预设 1.4 示例 1.4.1 示例1 1.4.2 示例2 1.rc参数设置 利用matplotlib绘图时为了让绘制出的图形更加好看&#xff0c;需要对参数进行设置rc参数设置。可以通过以下代码查看matplotli…...

图像去雨-雨线清除-图像处理-(计算机作业附代码)

背景 多年来&#xff0c;图像去雨已经被广泛研究&#xff0c;使用传统方法和基于学习的方法。然而&#xff0c;传统方法如高斯混合模型和字典学习方法耗时&#xff0c;并且无法很好地处理受到严重雨滴影响的图像块。 算法 通过考虑雨滴条状特性和角度分布&#xff0c;这个问…...

pycharm调整最大堆发挥最大

python程序运行时&#xff0c;怎么提高效率&#xff0c;设置pycharm最大堆过程如下&#xff1b; 一、进入设置pycharm最大堆&#xff1b; 二、进入设置pycharm最大堆&#xff1b; 如果8g设置为6g左右&#xff0c;占75%左右最佳...

uni-app 经验分享,从入门到离职(二)—— tabBar 底部导航栏实战基础篇

文章目录 &#x1f4cb;前言⏬关于专栏 &#x1f3af;关于小程序 tabbar 的一些知识&#x1f3af;创建一个基本的 tabBar&#x1f4dd;最后 &#x1f4cb;前言 这篇文章的内容主题是关于小程序的 tabBar 底部导航栏的入门使用和实战技巧。通过上一篇文章的基础&#xff0c;我们…...

【李沐】3.2线性回归从0开始实现

%matplotlib inline import random import torch from d2l import torch as d2l1、生成数据集&#xff1a; 看最后的效果&#xff0c;用正态分布弄了一些噪音 上面这个具体实现可以看书&#xff0c;又想了想还是上代码把&#xff1a; 按照上面生成噪声&#xff0c;其中最后那…...

一百五十六、Kettle——Linux上安装的Kettle9.3连接ClickHouse数据库(亲测,附流程截图)

一、目标 kettle9.3在Linux上安装好后&#xff0c;需要与ClickHouse数据库建立连接 二、前提准备 &#xff08;一&#xff09;在Linux已经安装好kettle并可以启动kettle &#xff08;二&#xff09;已知kettle和ClickHouse版本 1、kettle版本是9.3 2、ClickHouse版本是21…...

图数据库_Neo4j和SpringBoot整合使用_创建节点_删除节点_创建关系_使用CQL操作图谱---Neo4j图数据库工作笔记0009

首先需要引入依赖 springboot提供了一个spring data neo4j来操作 neo4j 可以看到它的架构 这个是下载下来的jar包来看看 有很多cypher对吧 可以看到就是通过封装的驱动来操作graph database 然后开始弄一下 首先添加依赖...