Python 类的继承实例详解

yipeiwu_com6年前Python基础

Python 类的继承详解

Python既然是面向对象的,当然支持类的继承,Python实现类的继承比JavaScript简单。

Parent类:

class Parent: 
 
  parentAttr = 100 
 
  def __init__(self): 
    print("parent Init") 
 
  def parentMethod(self): 
    print("parentMethod") 
   
  def setAttr(self,attr): 
    self.parentAttr = attr 
 
  def getAttr(self): 
    print("ParentAttr:",Parent.parentAttr) 

Child类

class Child(Parent): 
 
  def __init__(self): 
    print("child init") 
 
  def childMethod(self): 
    print("childMethod") 

调用

p1 = Parent(); 
p1.parentMethod(); 
 
c1 = Child(); 
c1.childMethod(); 

输出:

parent Init 
parentMethod 
child init 
childMethod 
Press any key to continue . . . 

Python支持多继承

class A:    # 定义类 A 
..... 
 
class B:     # 定义类 B 
..... 
 
class C(A, B):  # 继承类 A 和 B 
..... 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

python得到qq句柄,并显示在前台的方法

如下所示: # 导入模块 import win32gui win = win32gui.FindWindow(None, u'张三') # 将窗口调到前台 win32gui.Show...

Python编程中对super函数的正确理解和用法解析

当在子类需要调用父类的方法时,在python2.2之前,直接用类名调用类的方法,即非绑定的类方法,并把自身对象self作参数传进去。 class A(object): def...

浅谈python的深浅拷贝以及fromkeys的用法

浅谈python的深浅拷贝以及fromkeys的用法

1.join()的用法:使用前面的字符串.对后面的列表进行拼接,拼接结果是一个字符串 # lst = ["alex","dsb",'wusir','xsb'] # s = "".jo...

Python实现获取邮箱内容并解析的方法示例

本文实例讲述了Python实现获取邮箱内容并解析的方法。分享给大家供大家参考,具体如下: # -*- coding: utf-8 -*- from email.parser impo...

Django 限制用户访问频率的中间件的实现

一、定义限制访问频率的中间件 common/middleware.py import time from django.utils.deprecation import Mid...