zoukankan      html  css  js  c++  java
  • python-class(3)

     1 #!/usr/bin/env python
     2 #-*- coding:utf-8 -*-
     3 ############################
     4 #File Name: class3.py
     5 #Author: frank
     6 #Email: frank0903@aliyun.com
     7 #Created Time:2017-09-04 14:55:16
     8 ############################
     9 
    10 class Parent:
    11     parentAttr = 100
    12     def __init__(self):
    13         print "invoke construct of base class"
    14 
    15     def parentMethod(self):
    16         print "invode parentMethod"
    17 
    18     def setAttr(self, attr):
    19         Parent.parentAttr = attr
    20 
    21     def getAttr(self):
    22         print "attr of base class:", Parent.parentAttr
    23 
    24     def myMethod(self):
    25         print '调用父类方法'
    26 
    27 class Child(Parent):
    28     def __init__(self):
    29         print "invoke construct of sub class"
    30         
    31     def childMethod(self):
    32         print "invode childMethod"
    33 
    34     def myMethod(self):
    35         print '调用子类方法'
    36 
    37 c = Child()          # 实例化子类
    38 c.childMethod()      # 调用子类的方法
    39 c.parentMethod()     # 调用父类方法
    40 c.setAttr(200)       # 再次调用父类的方法 - 设置属性值
    41 c.getAttr()          # 再次调用父类的方法 - 获取属性值
    42 c.myMethod()

    python3.5 环境下运行:

     1 # -*- coding: utf-8 -*-
     2 """
     3 Created on Mon Jun 11 12:49:01 2018
     4 
     5 @author: Frank
     6 """
     7 
     8 class Parent:
     9     parentAttr = 100
    10     def __init__(self):
    11         print("invoke construct of base class")
    12 
    13     def parentMethod(self):
    14         print("invode parentMethod")
    15 
    16     def setAttr(self, attr):
    17         Parent.parentAttr = attr
    18 
    19     def getAttr(self):
    20         print("attr of base class:{}".format(Parent.parentAttr))
    21 
    22     def myMethod(self):
    23         print('调用父类方法')
    24 
    25 class Child(Parent):
    26     def __init__(self):
    27         print("invoke construct of sub class")
    28         
    29     def childMethod(self):
    30         print("invode childMethod")
    31 
    32     def myMethod(self):
    33         print('调用子类方法')
    34 
    35 c = Child()          # 实例化子类
    36 c.childMethod()      # 调用子类的方法
    37 c.parentMethod()     # 调用父类方法
    38 c.setAttr(200)       # 再次调用父类的方法 - 设置属性值
    39 c.getAttr()          # 再次调用父类的方法 - 获取属性值
    40 c.myMethod()         # override
    41 print("attr:{}".format(c.parentAttr))
  • 相关阅读:
    Python 读取Excel之xlrd篇
    Python读取文件基本方法
    Python 偏函数用法全方位解析
    如何表示只有一个元素的元祖
    Python对文本读写的操作方法【源码】
    jvm入门及理解(六)——垃圾回收与算法
    jvm入门及理解(五)——运行时数据区(虚拟机栈)
    jvm入门及理解(四)——运行时数据区(堆+方法区)
    jvm入门及理解(三)——运行时数据区(程序计数器+本地方法栈)
    jvm入门及理解(二)——类加载器子系统
  • 原文地址:https://www.cnblogs.com/black-mamba/p/7476803.html
Copyright © 2011-2022 走看看