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 
..... 

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

相关文章

Pytorch抽取网络层的Feature Map(Vgg)实例

这边我是需要得到图片在Vgg的5个block里relu后的Feature Map (其余网络只需要替换就可以了) 索引可以这样获得 vgg = models.vgg19(pretra...

PYTHON正则表达式 re模块使用说明

首先,运行 Python 解释器,导入 re 模块并编译一个 RE: #!python Python 2.2.2 (#1, Feb 10 2003, 12:57:01) >>...

PYTHON EVAL的用法及注意事项解析

前言 eval是Python的一个内置函数,这个函数的作用是,返回传入字符串的表达式的结果。想象一下变量赋值时,将等号右边的表达式写成字符串的格式,将这个字符串作为eval的参数,eva...

解决Python 命令行执行脚本时,提示导入的包找不到的问题

解决Python 命令行执行脚本时,提示导入的包找不到的问题

在Pydev能正常执行的脚本,在导出后在命令行执行,通常会报自己写的包导入时找不到。 一:报错原因 在PyDev中,test.py 中导入TestUserCase里面的py文件时,会写...

python plotly绘制直方图实例详解

python plotly绘制直方图实例详解

计算数值出现的次数 import cufflinks as cf cf.go_offline() import numpy as np import pandas as pd se...