搜索
首页后端开发Python教程聊聊Python里面的Self,是谁啊?

聊聊Python里面的Self,是谁啊?

May 15, 2023 am 08:01 AM
pythonself

聊聊Python里面的Self,是谁啊?

大家学Python面向对象的时候,总会遇到一个让人难以理解的存在:self。

这个self到底是谁啊,为什么每个类实例方法都有一个参数self,它到底有什么作用呢?

「先下结论:类实例化后,self即代表着实例(对象)本身。」

想要理解self有个最简单的方法,就是你把self当做「实例(对象)的身份证。」

Python的类不能直接使用,只有通过创建实例(对象)才能发挥它的功能,每个实例(对象)都是独一无二的,它可以调用类的方法、属性。类就像灵魂附体一样,让实例(对象)有了自己(self)的功能。

聊聊Python里面的Self,是谁啊?

初学者会发现,类的方法(构造方法和实例方法)中都会有一个固定参数self,其实这个参数就是代表着实例(对象)本身,就像是一个身份证,实例可以凭着身份证去调用类方法。

聊聊Python里面的Self,是谁啊?

类比人类,人类就是一个Python类,每个个体的人代表着实例(对象),而每个人的身份证代表的Python中self,每个人可以凭借身份证去上大学、坐高铁、住酒店...(方法),而Python中的实例(对象)也可以凭着self去调用类的方法。

聊聊Python里面的Self,是谁啊?

上面是用类比的方法解释了下self的含义,说到底self就是代表着实例本身,「当某个实例(对象)调用类方法时,该对象会把自身的引用作为第一个参数自动传给该方法,而这第一个参数就是self。」

而且self只是约定俗成的写法,你可以用任何其他名称代替self,不会改变代码含义,只不过我们一般不这样做。

为了更好的说明self的作用,我们来举个例子,下面有一个Students类:

class Students:
# 构造方法
def __init__(self,name):
self.name = name
# 实例方法
def study(self,examination_results):
self.examination_results = examination_results
print("同学{}的考试分数是{}".format(self.name,self.examination_results))
print("该实例对象的地址是{}".format(self))

先来个实例student_a。

studend_a = Students('studend_a')
print(studend_a.name)

结果打印出:studend_a。

再来个实例student_b。

studend_b = Students('studend_b')
print(studend_b.name)

结果打印出:studend_b。

可以看出,实例(对象)不一样,打印出的结果也不一样,当类被实例化后,self.name其实就等于实例(对象).name。

还是以刚刚的代码为例,我们再来调用里面的实例方法,里面会打印出self,就能看得更加明显了。

实例student_a:

studend_a = Students('studend_a')
print(studend_a.study(80))

输出结果:

同学studend_a的考试分数是80 该实例对象的地址是。

实例student_b:

studend_b = Students('studend_b')
print(studend_b.study(80))

输出结果:

同学studend_b的考试分数是80 该实例对象的地址是。

大家能清楚看到两个实例打印出的self是不一样的,因为self代表着实例(对象)本身。

以实例student_b来说,打印self出现下面对象信息。

<__main__.students object at>。

如果再打印 student_b,会出现同样的结果。

print(student_b)

输出:

<__main__.students object at>。

这个时候是不是就清楚了,类实例化后,self即代表着实例(对象)本身。

以上是聊聊Python里面的Self,是谁啊?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:51CTO.COM。如有侵权,请联系admin@php.cn删除
可以在Python数组中存储哪些数据类型?可以在Python数组中存储哪些数据类型?Apr 27, 2025 am 12:11 AM

pythonlistscanStoryDatatepe,ArrayModulearRaysStoreOneType,and numpyArraySareSareAraysareSareAraysareSareComputations.1)列出sareversArversAtileButlessMemory-Felide.2)arraymoduleareareMogeMogeNareSaremogeNormogeNoreSoustAta.3)

如果您尝试将错误的数据类型的值存储在Python数组中,该怎么办?如果您尝试将错误的数据类型的值存储在Python数组中,该怎么办?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Python标准库的哪一部分是:列表或数组?Python标准库的哪一部分是:列表或数组?Apr 27, 2025 am 12:03 AM

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

您应该检查脚本是否使用错误的Python版本执行?您应该检查脚本是否使用错误的Python版本执行?Apr 27, 2025 am 12:01 AM

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

在Python阵列上可以执行哪些常见操作?在Python阵列上可以执行哪些常见操作?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

在哪些类型的应用程序中,Numpy数组常用?在哪些类型的应用程序中,Numpy数组常用?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

您什么时候选择在Python中的列表上使用数组?您什么时候选择在Python中的列表上使用数组?Apr 26, 2025 am 12:12 AM

useanArray.ArarayoveralistinpythonwhendeAlingwithHomeSdata,performance-Caliticalcode,orinterFacingWithCcccode.1)同质性data:arrayssavememorywithtypedelements.2)绩效code-performance-clitionalcode-clitadialcode-critical-clitical-clitical-clitical-clitaine code:araysofferferbetterperperperformenterperformanceformanceformancefornalumericalicalialical.3)

所有列表操作是否由数组支持,反之亦然?为什么或为什么不呢?所有列表操作是否由数组支持,反之亦然?为什么或为什么不呢?Apr 26, 2025 am 12:05 AM

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactssperformance.2)listssdonotguaranteeconeeconeconstanttanttanttanttanttanttanttanttimecomplecomecomecomplecomecomecomecomecomecomplecomectaccesslikearrikearraysodo。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用