python类继承用法实例分析


Posted in Python onMay 27, 2015

本文实例讲述了python类继承用法。分享给大家供大家参考。具体如下:

help('object') # test
class Class1(object):
  """
  Class1 inherits the most basic container class object (just a place holder)
  this is the newer class writing convention, adding (object) is "still" optional
  """
  k = 7
  def __init__(self, color='green'):
    """
    Special method __init__() is called first (acts as Constructor).
    It brings in data from outside the class like the variable color.
    (in this case color is also set to a default value of green)
    The first parameter of any method/function in the class is always self,
    the name self is used by convention. Assigning color to self.color allows it
    to be passed to all methods within the class. Think of self as a carrier,
    or if you want impress folks call it target instance object.
    The variable k is assigned a value in the class, but outside of the methods.
    You can access k in a method using self.k
    """
    self.color = color
  def Hello1(self):
    print "Hello from Class1!"
  def printColor(self):
    """in this case self allows color to be passed"""
    print "I like the color", self.color
  def __localHello(self):
    """
    A variable or function with a double underline prefix and no or max. single
    underline postfix is considered private to the class and is not inherited or
    accessible outside the class.
    """
    print "A hardy Hello only used within the class!"
 
class Class2(Class1):
  """
  Class2 inherits Class1 (Class2 is the subclass, Class1 the base or superclass)
  Class1 has to be coded before Class2 for this to work!!!
  Class2 can now use any method of Class1, and even the variable k
  """
  def Hello2(self):
    print "Hello from Class2!"
    print self.k, "is my favorite number"
   
# the color blue is passed to __init__()
c1 = Class1('blue')
# Class2 inherited method __init__() from Class1
# if you used c2 = Class2(), the default color green would be picked
c2 = Class2('red')
print '-'*20
print "Class1 says hello:"
c1.Hello1()
print '-'*20
print "Class2 says a Class1 hello:"
c2.Hello1()
print '-'*20
print "Class2 says its own hello:"
c2.Hello2()
print '-'*20
print "Class1 color via __init__():"
c1.printColor()
print '-'*20
print "Class2 color via inherited __init__() and printColor():"
c2.printColor()
print '-'*20
print "Class1 changes its mind about the color:"
c1 = Class1('yellow') # same as: c1.__init__('yellow')
c1.printColor()
print '-'*20
print "Wonder what Class2 has to say now:"
c2.printColor()
print '-'*20
# this would give an error! Class1 does not have a method Hello2()
if hasattr(Class1, "Hello2"):
  print c1.Hello2()
else:
  print "Class1 does not contain method Hello2()"
# check inheritance
if issubclass(Class2, Class1):
  print "Class2 is a subclass of Class1, or Class2 has inherited Class1"
# you can access variable k contained in Class1
print "Variable k from Class1 =", c1.k
print '-'*20
# this would give an error! You cannot access a class private method
if hasattr(Class1, "__localHello()"):
  print c1.__localHello()
else:
  print "No access to Class1 private method __localHello()"

运行结果如下:

Help on class object in module __builtin__:

class object
 | The most base type

--------------------
Class1 says hello:
Hello from Class1!
--------------------
Class2 says a Class1 hello:
Hello from Class1!
--------------------
Class2 says its own hello:
Hello from Class2!
7 is my favorite number
--------------------
Class1 color via __init__():
I like the color blue
--------------------
Class2 color via inherited __init__() and printColor():
I like the color red
--------------------
Class1 changes its mind about the color:
I like the color yellow
--------------------
Wonder what Class2 has to say now:
I like the color red
--------------------
Class1 does not contain method Hello2()
Class2 is a subclass of Class1, or Class2 has inherited Class1
Variable k from Class1 = 7
--------------------
No access to Class1 private method __localHello()

希望本文所述对大家的Python程序设计有所帮助。

Python 相关文章推荐
python为tornado添加recaptcha验证码功能
Feb 26 Python
Python的Bottle框架中获取制定cookie的教程
Apr 24 Python
Python通过正则表达式选取callback的方法
Jul 18 Python
在python中安装basemap的教程
Sep 20 Python
Python datetime和unix时间戳之间相互转换的讲解
Apr 01 Python
python和mysql交互操作实例详解【基于pymysql库】
Jun 04 Python
PyTorch中的C++扩展实现
Apr 02 Python
pandas DataFrame 数据选取,修改,切片的实现
Apr 24 Python
python3.6环境下安装freetype库和基本使用方法(推荐)
May 10 Python
Python matplotlib读取excel数据并用for循环画多个子图subplot操作
Jul 14 Python
OpenCV读取与写入图片的实现
Oct 13 Python
Pandas数据分析的一些常用小技巧
Feb 07 Python
python显示生日是星期几的方法
May 27 #Python
python中zip和unzip数据的方法
May 27 #Python
Python pickle模块用法实例分析
May 27 #Python
Python创建模块及模块导入的方法
May 27 #Python
Python类的用法实例浅析
May 27 #Python
Python socket编程实例详解
May 27 #Python
Python简单删除目录下文件以及文件夹的方法
May 27 #Python
You might like
ThinkPHP表单自动验证实例
2014/10/13 PHP
php结合redis高并发下发帖、发微博的实现方法
2016/12/15 PHP
不错的新闻标题颜色效果
2006/12/10 Javascript
json2.js的初步学习与了解
2011/10/06 Javascript
javascript写的简单的计算器,内容很多,方法实用,推荐
2011/12/29 Javascript
jQuery的remove()方法使用详解
2015/08/11 Javascript
JavaScript变量的作用域全解析
2015/08/14 Javascript
JS实现CheckBox复选框全选、不选或全不选功能
2020/07/28 Javascript
详解JavaScript中|单竖杠运算符的使用方法
2016/05/23 Javascript
JavaScript知识点总结(十一)之js中的Object类详解
2016/05/31 Javascript
JS去除字符串中空格的方法
2017/02/14 Javascript
轻松学习Javascript闭包
2017/03/01 Javascript
mac下的nodejs环境安装的步骤
2017/05/24 NodeJs
Django+Vue.js搭建前后端分离项目的示例
2017/08/07 Javascript
用js屏蔽被http劫持的浮动广告实现方法
2017/08/10 Javascript
微信小程序五子棋游戏的悔棋实现方法【附demo源码下载】
2019/02/20 Javascript
微信小程序学习笔记之函数定义、页面渲染图文详解
2019/03/28 Javascript
Vue中通过属性绑定为元素绑定style行内样式的实例代码
2020/04/30 Javascript
[08:42]DOTA2每周TOP10 精彩击杀集锦vol.2
2014/06/25 DOTA
python基础教程之Filter使用方法
2017/01/17 Python
django表单的Widgets使用详解
2019/07/22 Python
Python数据可视化实现漏斗图过程图解
2020/07/20 Python
日本最大的眼镜购物网站:Oh My Glasses
2016/11/13 全球购物
Amara美国站:英国高端家居礼品网站,世界各地的奢侈家具品牌
2017/07/26 全球购物
医药营销个人求职信范文
2014/02/07 职场文书
火车来了教学反思
2014/02/11 职场文书
感恩寄语大全
2014/04/11 职场文书
安全施工标语
2014/06/07 职场文书
没有孩子的离婚协议书怎么写
2014/09/17 职场文书
文员转正自我鉴定怎么写
2014/09/29 职场文书
无刑事犯罪记录证明范本
2014/09/29 职场文书
学校领导四风问题整改措施思想汇报
2014/10/09 职场文书
简历自我评价范文
2019/04/24 职场文书
Python基于百度API识别并提取图片中文字
2021/06/27 Python
numpy array找出符合条件的数并赋值的示例代码
2022/06/01 Python
使用Redis实现分布式锁的方法
2022/06/16 Redis