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 相关文章推荐
pyside写ui界面入门示例
Jan 22 Python
Python自动化构建工具scons使用入门笔记
Mar 10 Python
python中__call__内置函数用法实例
Jun 04 Python
Python3.4编程实现简单抓取爬虫功能示例
Sep 14 Python
Bottle框架中的装饰器类和描述符应用详解
Oct 28 Python
python中format()函数的简单使用教程
Mar 14 Python
pandas DataFrame数据转为list的方法
Apr 11 Python
python将字符串以utf-8格式保存在txt文件中的方法
Oct 30 Python
Python实现京东秒杀功能代码
May 16 Python
python基于Selenium的web自动化框架
Jul 14 Python
python导入不同目录下的自定义模块过程解析
Nov 18 Python
使用TensorFlow直接获取处理MNIST数据方式
Feb 10 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
第十四节--命名空间
2006/11/16 PHP
php使用GD创建保持宽高比缩略图的方法
2015/04/17 PHP
用javascript getComputedStyle获取和设置style的原理
2008/10/10 Javascript
xml文档转换工具,附图表例子(hta)
2010/11/17 Javascript
nodejs的10个性能优化技巧
2014/07/15 NodeJs
Nodejs学习笔记之Global Objects全局对象
2015/01/13 NodeJs
JavaScript中闭包之浅析解读(必看篇)
2016/08/25 Javascript
iscroll-probe实现下拉刷新和下拉加载效果
2017/06/28 Javascript
H5实现仿flash效果的实现代码
2017/09/29 Javascript
在react-router4中进行代码拆分的方法(基于webpack)
2018/03/08 Javascript
element-ui 的el-button组件中添加自定义颜色和图标的实现方法
2018/10/26 Javascript
element-ui中el-upload多文件一次性上传的实现
2020/12/02 Javascript
Vue中的nextTick作用和几个简单的使用场景
2021/01/25 Vue.js
python sqlobject(mysql)中文乱码解决方法
2008/11/14 Python
java直接调用python脚本的例子
2014/02/16 Python
python 创建一维的0向量实例
2019/12/02 Python
Python3中configparser模块读写ini文件并解析配置的用法详解
2020/02/18 Python
Anaconda3+tensorflow2.0.0+PyCharm安装与环境搭建(图文)
2020/02/18 Python
完美解决python针对hdfs上传和下载的问题
2020/06/05 Python
纯CSS3实现Material Design效果
2017/03/09 HTML / CSS
CSS书写规范、顺序和命名规则
2014/03/06 HTML / CSS
意大利火车票和铁路通行证专家:ItaliaRail
2019/01/22 全球购物
描述一下JVM加载class文件的原理机制
2013/12/08 面试题
TCP/IP的分层模型
2013/10/27 面试题
车间副主任岗位职责
2013/12/24 职场文书
乔迁宴答谢词
2014/01/21 职场文书
讲文明树新风公益广告宣传方案
2014/02/25 职场文书
《英英学古诗》教学反思
2014/04/11 职场文书
群众路线批评与自我批评发言稿
2014/10/16 职场文书
2015关爱留守儿童工作总结
2014/12/12 职场文书
学习型家庭事迹材料
2014/12/20 职场文书
2015年幼师个人工作总结
2015/10/15 职场文书
Mysql MVCC机制原理详解
2021/04/20 MySQL
「天才王子的赤字国家重生术」妮妮姆·拉雷粘土人开订
2022/03/21 日漫
《勇者辞职不干了》上卷BD发售宣传CM公开
2022/04/08 日漫
MySQL中order by的执行过程
2022/06/05 MySQL