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读取mp3中ID3信息的方法
Mar 05 Python
Python中使用语句导入模块或包的机制研究
Mar 30 Python
详解Golang 与python中的字符串反转
Jul 21 Python
python中 logging的使用详解
Oct 25 Python
Python编程实现从字典中提取子集的方法分析
Feb 09 Python
python取代netcat过程分析
Feb 10 Python
tensorflow实现KNN识别MNIST
Mar 12 Python
Python 类的特殊成员解析
Jun 20 Python
pycharm设置鼠标悬停查看方法设置
Jul 29 Python
python爬虫可以爬什么
Jun 16 Python
使用Tensorflow-GPU禁用GPU设置(CPU与GPU速度对比)
Jun 30 Python
Django:使用filter的pk进行多值查询操作
Jul 15 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
PHP与MySQL开发的8个技巧小结
2010/12/17 PHP
对YUI扩展的Gird组件 Part-1
2007/03/10 Javascript
JavaScript 继承使用分析
2011/05/12 Javascript
js时间日期和毫秒的相互转换
2013/02/22 Javascript
js 获取(接收)地址栏参数值的方法
2013/04/01 Javascript
jquery重复提交请求的原因浅析
2014/05/23 Javascript
jQuery oLoader实现的加载图片和页面效果
2015/03/14 Javascript
HTML5+setCutomValidity()函数验证表单实例分享
2015/04/24 Javascript
使用Node.js为其他程序编写扩展的基本方法
2015/06/23 Javascript
JavaScript学习笔记之数组求和方法
2016/03/23 Javascript
jQuery实现贪吃蛇小游戏(附源码下载)
2017/03/04 Javascript
javascript 中Cookie读、写与删除操作
2017/03/29 Javascript
Angular2开发环境搭建教程之VS Code
2017/12/15 Javascript
基于 Vue.js 2.0 酷炫自适应背景视频登录页面实现方式
2018/01/17 Javascript
vue移动端监听滚动条高度的实现方法
2018/09/03 Javascript
Vue $emit $refs子父组件间方法的调用实例
2018/09/12 Javascript
mpvue微信小程序多列选择器用法之省份城市选择的实现
2019/03/07 Javascript
JavaScript面试技巧之数组的一些不low操作
2019/03/22 Javascript
Element Carousel 走马灯的具体实现
2020/07/26 Javascript
如何利用JavaScript编写一个格斗小游戏
2021/01/06 Javascript
python变量不能以数字打头详解
2016/07/06 Python
python urllib爬取百度云连接的实例代码
2017/06/19 Python
python中matplotlib实现最小二乘法拟合的过程详解
2017/07/11 Python
对python函数签名的方法详解
2019/01/22 Python
用Python识别人脸,人种等各种信息
2019/07/15 Python
Python高并发和多线程有什么关系
2020/11/14 Python
html5 canvas-1.canvas介绍(hello canvas)
2013/01/07 HTML / CSS
美国派对用品及装饰品网上商店:Shindigz
2016/07/30 全球购物
现代绅士日常奢侈品:Todd Snyder
2019/12/13 全球购物
实习生自我评价
2014/01/18 职场文书
高中军训感言1000字
2014/03/01 职场文书
《傅雷家书》教学反思
2014/04/20 职场文书
小学优秀教师事迹材料
2014/12/16 职场文书
三八红旗手事迹材料
2014/12/26 职场文书
jquery插件实现代码雨特效
2021/04/24 jQuery
详解解Django 多对多表关系的三种创建方式
2021/08/23 Python