跳至主要内容

python 类class

    python 中的基本数据类型一次仅指一种数据。

    如果您可以声明一种本身包含多个数据类型并且可以在任何函数的帮助下使用它们的数据类型,那会怎样?Python 类class为您提供了这个机会。

“name”和“age”是“Person”类的两个成员变量。每次我们声明这个类的一个对象时,它都会包含这两个变量作为它的成员。这部分是可选的,因为它们可以由构造函数初始化。

Python 类构造函数是创建类的新对象时要执行的第一段代码
构造函数可用于将值放入成员变量中。您还可以在构造函数中打印消息以确认对象是否已创建。
一旦我们了解了 python 继承,我们将了解构造函数的更大作用。构造函数方法以 def __init__ 开头。之后,第一个参数必须是“self”,因为它传递对类本身实例的引用。您还可以添加其他参数,如示例中所示的方式。'person_name' 和 'person_age' 是要创建新对象时发送的两个参数。
 
在python中创建对象的方式非常简单。首先,您输入新对象的名称,后跟赋值运算符和带参数的类名称(在构造函数中定义)。请记住,参数的数量和类型应与构造函数中接收到的参数兼容。
创建对象后,可以调用成员方法并访问成员属性(前提是它们是可访问的)。






  1. # definition of the superclass starts here  
  2. class Person:  
  3.     # initializing the variables  
  4.     name = ""  
  5.     age = 0  
  6.     #defining constructor  
  7.     def __init__(self, person_name, person_age):
  8.         self.name = person_name
  9.         self.age = person_age
  10.  
  11.     # defining class methods
  12.     def show_name(self):
  13.         print(self.name)
  14.  
  15.     def show_age(self):
  16.         print(self.age)
  17. # end of superclass definition  

  18. #definition of subclass starts here
  19. class Student(Person): # Person is the  superclass and Student is the subclass
  20.     studentId = ""
  21.    
  22.     def __init__(self, student_name, student_age, student_id):
  23.         # Calling the superclass constructor and sending values of attributes.
  24. # Python super() 函数允许我们隐式地引用超类
  25.         # 等同于下行 super().__init__(student_name, student_age)
  26.         Person.__init__(self, student_name, student_age)
  27.         self.student_id = student_id  
  28.  
  29.     def get_id(self):  
  30.         return self.student_id  #returns the value of student id
  31. #end of subclass definition
  32.  
  33. # Create an object of the superclass
  34. person1 = Person("Richard", 23)
  35. # call member methods of the objects
  36. person1.show_age()
  37. # Create an object of the subclass
  38. student1 = Student("Max", 22, "102")
  39. print(student1.get_id())
  40. student1.show_name()
  41.  


在多级继承的情况下,它会引用哪个类?好吧,Python super() 将始终引用直接超类
从输出中我们可以清楚地看到,首先__init__()调用了类 C的函数,然后是类 B,然后是类 A。调用sub_method()函数也发生了类似的事情。

  1. class A:
  2.     def __init__(self):
  3.         print('Initializing: class A')
  4.  
  5.     def sub_method(self, b):
  6.         print('Printing from class A:', b)
  7.  
  8.  
  9. class B(A):
  10.     def __init__(self):
  11.         print('Initializing: class B')
  12.         super().__init__()
  13.  
  14.     def sub_method(self, b):
  15.         print('Printing from class B:', b)
  16.         super().sub_method(b + 1)
  17.  
  18.  
  19. class C(B):
  20.     def __init__(self):
  21.         print('Initializing: class C')
  22.         super().__init__()
  23.  
  24.     def sub_method(self, b):
  25.         print('Printing from class C:', b)
  26.         super().sub_method(b + 1)
  27.  
  28.  
  29. if __name__ == '__main__':
  30.     c = C()
  31.     c.sub_method(1)
  32.  
  33. # Initializing: class C
  34. # Initializing: class B
  35. # Initializing: class A
  36. # Printing from class C: 1
  37. # Printing from class B: 2
  38. # Printing from class A: 3
  39.  

使用python多重继承解决冲突

  1.      
  2. #definition of the class starts here  
  3. class Person:  
  4.     #defining constructor  
  5.     def __init__(self, personName, personAge):  
  6.         self.name = personName  
  7.         self.age = personAge  
  8.  
  9.     #defining class methods  
  10.     def showName(self):  
  11.         print(self.name)  
  12.  
  13.     def showAge(self):  
  14.         print(self.age)  
  15.  
  16.     #end of class definition  
  17.  
  18. # defining another class  
  19. class Student: # Person is the  
  20.     def __init__(self, studentId):  
  21.         self.studentId = studentId  
  22.  
  23.     def getId(self):  
  24.         return self.studentId  
  25.  
  26.  
  27. class Resident(Person, Student): # extends both Person and Student class  
  28.     def __init__(self, name, age, id):  
  29.         Person.__init__(self, name, age)  
  30.         Student.__init__(self, id)  
  31.  
  32.  
  33. # Create an object of the subclass  
  34. resident1 = Resident('John', 30, '102')  
  35. resident1.showName()  
  36. print(resident1.getId())  
  37. # John
  38. # 102
  39.  
  40. # 使用python多重继承解决冲突
  41. class A:  
  42.     def __init__(self):  
  43.         self.name = 'John'  
  44.         self.age = 23  
  45.  
  46.     def getName(self):  
  47.         return self.name  
  48.  
  49.  
  50. class B:  
  51.     def __init__(self):  
  52.         self.name = 'Richard'  
  53.         self.id = '32'  
  54.  
  55.     def getName(self):  
  56.         return self.name  
  57.  
  58.  
  59. class C(A, B):  
  60.     def __init__(self):  
  61.         A.__init__(self)  
  62.         B.__init__(self)  
  63.  
  64.     def getName(self):  
  65.         return self.name  
  66.  
  67. C1 = C()  
  68. print(C1.getName())
  69. # 打印出来的名字是“Richard”而不是“John”。
  70. # 让我们试着了解这里发生了什么。在 C 的构造函数中,调用的第一个构造函数是 A 的构造函数。因此,C 中 name 的值变为与 A 中 name 的值相同。
  71. # 但之后,当调用 B 的构造函数时,name 的值C 中的名称被 B 中的 name 值覆盖。
  72. # 因此,C 的 name 属性在打印时保留值 'Richard'。即使我们将 C 类声明为:Class C(B, A)
  73. # 层次结构完全取决于子类中 __init__() 调用的顺序。为了完美地处理它,有一个名为 MRO(方法解析顺序)的协议
  74.  
  75.  
  76.        
  77. class A:  
  78.     def __init__(self):  
  79.         super().__init__()  
  80.         self.name = 'John'  
  81.         self.age = 23  
  82.  
  83.     def getName(self):  
  84.         return self.name  
  85.  
  86.  
  87. class B:  
  88.     def __init__(self):  
  89.         super().__init__()  
  90.         self.name = 'Richard'  
  91.         self.id = '32'  
  92.  
  93.     def getName(self):  
  94.         return self.name  
  95.  
  96.  
  97. class C(A, B):  
  98.     def __init__(self):  
  99.         super().__init__()  
  100.  
  101.     def getName(self):  
  102.         return self.name  
  103.  
  104. C1 = C()  
  105. print(C1.getName())  
  106.  
  107.  
  108. # class C(A, B):打印出来的名字是“John”。
  109. # MRO 以从左到右的方式深度工作。__init__ 方法中的 super() 表示下一个层次结构中的类。
  110. # 首先C的super()表示A。然后A的构造函数中的super寻找它的超类。如果没有找到,则执行其余代码并返回。
  111. # 所以这里调用构造函数的顺序是:C -> A -> B
  112. # 如果我们调用print(C.__mro__),那么我们就可以看到MRO的traceroute了。
  113. # (<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)
  114. # 一旦调用了 A 的构造函数并访问了属性“name”,它就不会访问 B 中的属性“name”。为了使用 python 多重继承,必须更好地理解 MRO。
  115. # class C(B, A):打印出来的名字是“Richard”。调用print(C.__mro__)
  116. # (<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>)
  117.  

评论

此博客中的热门博文

学习地址

清华大学计算机系课程攻略 https://github.com/PKUanonym/REKCARC-TSC-UHT 浙江大学课程攻略共享计划 https://github.com/QSCTech/zju-icicles https://home.unicode.org/ 世界上的每个人都应该能够在手机和电脑上使用自己的语言。 http://codecanyon.net   初次看到这个网站,小伙伴们表示都惊呆了。原来代码也可以放在网上卖的?!! 很多coder上传了各种代码,每个代码都明码标价。看了下销售排行,有的19刀的卖了3万多份,额di神啊。可以看到代码的演示效果,真的很漂亮。代码以php、wordpress主题、Javascript、css为主,偏前台。 https://www.lintcode.com/ 算法学习网站,上去每天刷两道算法题,走遍天下都不怕。 https://www.codecademy.com/ 包含在线编程练习和课程视频 https://www.reddit.com/ 包含有趣的编程挑战题,即使不会写,也可以查看他人的解决方法。 https://ideone.com/ 在线编译器,可运行,可查看代码示例。 http://it-ebooks.info/ 大型电子图书馆,可即时免费下载书籍。 刷题 https://github.com/jackfrued/Python-100-Days https://github.com/kenwoodjw/python_interview_question 面试问题 https://github.com/kenwoodjw/python_interview_question https://www.journaldev.com/15490/python-interview-questions#python-interpreter HTTP 身份验证 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Authentication RESTful 架构详解 https://www.runoob.com/w3cnote/restful-architecture.html https://www.rosettacode.org/wiki/Rosetta_C...

PDF处理

虚拟pdf打印机 pdfFactory  https://fineprint.com PDFCreator  https://www.pdfforge.org 开源 cutepdf https://www.cutepdf.com/index.htm Doro PDF Writer http://www.the-sz.com/products/doro PdfScribe  https://github.com/stchan/PdfScribe/releases pdf阅读器 Sumatra PDF https://www.sumatrapdfreader.org/ 为什么 Python 用于 PDF 处理  如您所知,PDF 处理属于文本分析。 大多数文本分析库或框架仅使用 Python 设计。 这为文本分析提供了优势。 还有一件事,您永远无法在现有的机器学习或自然语言处理框架中直接处理 pdf。 除非他们为此证明了显式接口。 我们必须先将pdf转换为文本。 我们可以使用下述任何库轻松实现这一点。 在线转换pdf Sejda https://www.sejda.com/pdf-editor 每个文档 200 页的免费限制 https://www.pdf2go.com/ https://tools.pdfforge.org/extract-text PDF24 Tools https://tools.pdf24.org/zh/ 免费且易于使用的在线PDF工具 FreeOCR http://www.paperfile.net/ 适用于Windows的免费光学字符识别软件,支持大多数Twain扫描仪的扫描,还可以打开大多数扫描的PDF和多页Tiff图像以及流行的图像文件格式,FreeOCR输出纯文本,可以直接导出为Microsoft Word格式。 不支持中文 wkhtmltopdf 和 wkhtmltoimage 是使用 QT Webkit 渲染引擎将 HTML 渲染为 PDF 和各种图像格式的命令行工具。这些完全“无头”运行,不需要显示或显示服务。 https://wkhtmltopdf.org/ django-wkhtmltopdf 允许 Django 站点输出动态 PDF。它利用 wkhtmltopdf 库,允许您使用您知道...

安卓 之 apk下载、ADB、 scrcpy

Apk下载 下载离线安装apk https://www.apkmirror.com/ 免费和安全的Android APK下载 https://apkpure.com/ 被暴雷,有植入 https://apps.evozi.com/apk-downloader/ 可以将Google Play( https://play.google.com )中的apk文件所在网址直接下载到台式机和设备上 https://f-droid.org/zh_Hans/ F-Droid 是一个 Android 平台上 FOSS(Free and Open Source Software,自由开源软件)的目录,并提供下载安装支持。使用客户端可以更轻松地浏览、安装及跟进设备上的应用更新。 https://gitlab.com/AuroraOSS/AuroraStore Aurora商店 是Google Play商店的非官方FOSS客户,设计典雅。 Aurora商店不仅下载,更新和搜索Play商店等应用 https://github.com/OpenTracksApp/OpenTracks OpenTracks是一款运动跟踪应用程序,完全尊重您的隐私。 Tasker https://tasker.joaoapps.com/ 是一款适用于Android的应用程序,它可以根据用户定义的配置文件中的上下文、可点击或定时的主屏幕小部件来执行任务。它无需root或特殊的主屏幕就能控制Android设备。 AsciiCam AsciiCam可以从您的相机指向的任何位置实时生成ASCII图像。选择黑白,原色或全彩,拍照,并将其作为图像或HTML共享。您还可以在库中创建ASCII版本的图片,并且每次使用标准相机应用程序拍摄照片时,也可以选择自动生成ASCII版本。 AsciiCam是完全免费和开源的。 Apk1安装器 优化微信apk文件接收体验。 微信收到apk文件会加 ".1" 后缀导致打不开,必须自己手动找到文件重命名去掉后缀。 使用本安装器就可以在微信内,潇洒地点击直接打开。甚至可以在安装器内浏览apk1文件历史接收记录。 ADB ADB全名是 Android Debug Bridge,是开发或使用Android时很常用的工具。可以从电脑通过USB连线到Android手机上 https:...