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中使用SimpleParse模块进行解析的教程
Apr 11 Python
python学习之matplotlib绘制散点图实例
Dec 09 Python
Python实现的求解最大公约数算法示例
May 03 Python
利用Python写一个爬妹子的爬虫
Jun 08 Python
对Python2与Python3中__bool__方法的差异详解
Nov 01 Python
PyCharm 设置SciView工具窗口的方法
Jan 15 Python
django url到views参数传递的实例
Jul 19 Python
django 中QuerySet特性功能详解
Jul 25 Python
Python 利用Entrez库筛选下载PubMed文献摘要的示例
Nov 24 Python
Python虚拟环境virtualenv是如何使用的
Jun 20 Python
Python初学者必备的文件读写指南
Jun 23 Python
Pytest中conftest.py的用法
Jun 27 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/10/09 PHP
php框架CodeIgniter使用redis的方法分析
2018/04/13 PHP
PHP5.6.8连接SQL Server 2008 R2数据库常用技巧分析总结
2019/05/06 PHP
YII2.0框架行为(Behavior)深入详解
2019/07/26 PHP
js函数般调用正则
2008/04/08 Javascript
基于JQuery的列表拖动排序实现代码
2013/10/01 Javascript
jQuery使用cookie与json简单实现购物车功能
2016/04/15 Javascript
js实现的页面加载完毕之前loading提示效果完整示例【附demo源码下载】
2016/08/02 Javascript
JavaScript中闭包之浅析解读(必看篇)
2016/08/25 Javascript
js正则取值的结果数组调试方法
2018/10/10 Javascript
JS实现的贪吃蛇游戏案例详解
2019/05/01 Javascript
小程序如何使用分包加载的实现方法
2019/05/22 Javascript
微信接入之获取用户头像的方法步骤
2019/09/23 Javascript
解决vue+ element ui 表单验证有值但验证失败问题
2020/01/16 Javascript
[48:53]2014 DOTA2华西杯精英邀请赛 5 25 LGD VS VG第一场
2014/05/26 DOTA
Python threading多线程编程实例
2014/09/18 Python
通过Python来使用七牛云存储的方法详解
2015/08/07 Python
python版简单工厂模式
2017/10/16 Python
Pyinstaller将py打包成exe的实例
2018/03/31 Python
python调用百度语音识别api
2018/08/30 Python
DES加密解密算法之python实现版(图文并茂)
2018/12/06 Python
python Django里CSRF 对应策略详解
2019/08/05 Python
解决Python图形界面中设置尺寸的问题
2020/03/05 Python
手把手教你配置JupyterLab 环境的实现
2021/02/02 Python
Zatchels官网:英国剑桥包品牌
2021/01/12 全球购物
盛大二次面试题
2016/11/18 面试题
网游商务专员求职信
2013/10/15 职场文书
保安拾金不昧表扬信
2014/01/15 职场文书
决定成败的关键——创业计划书
2014/01/24 职场文书
淘宝活动策划方案
2014/02/06 职场文书
2014年社区植树节活动方案
2014/02/28 职场文书
安全月活动总结
2014/05/05 职场文书
公民代理授权委托书
2014/09/24 职场文书
css布局巧妙技巧之css三角示例的运用
2022/03/16 HTML / CSS
MySQL的意向共享锁、意向排它锁和死锁
2022/07/15 MySQL
CSS浮动引起的高度塌陷问题
2022/08/05 HTML / CSS