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))
原文地址:https://www.cnblogs.com/black-mamba/p/7476803.html