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编写爬虫小程序
May 14 Python
python3中dict(字典)的使用方法示例
Mar 22 Python
使用Python实现博客上进行自动翻页
Aug 23 Python
Python通过future处理并发问题
Oct 17 Python
python 统计一个列表当中的每一个元素出现了多少次的方法
Nov 14 Python
python3爬虫获取html内容及各属性值的方法
Dec 17 Python
获取django框架orm query执行的sql语句实现方法分析
Jun 20 Python
Python检查图片是否损坏及图片类型是否正确过程详解
Sep 30 Python
Python下利用BeautifulSoup解析HTML的实现
Jan 17 Python
python正则过滤字母、中文、数字及特殊字符方法详解
Feb 11 Python
python 函数嵌套及多函数共同运行知识点讲解
Mar 03 Python
python3 删除所有自定义变量的操作
Apr 08 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初学者的8点有效建议
2010/11/20 PHP
Yii查询生成器(Query Builder)用法实例教程
2014/09/04 PHP
php中的常用魔术方法汇总
2016/02/14 PHP
PHP递归实现层级树状展开
2016/04/01 PHP
PHP单态模式简单用法示例
2016/11/16 PHP
prototype.js的Ajax对象
2006/09/23 Javascript
几个常用的JavaScript字符串处理函数 - split()、join()、substring()和indexOf()
2009/06/02 Javascript
jquery插件制作 自增长输入框实现代码
2012/08/17 jQuery
简略说明Javascript中的= =(等于)与= = =(全等于)区别
2013/04/16 Javascript
js实现浏览器的各种菜单命令比如打印、查看源文件等等
2013/10/24 Javascript
JavaScript简单实现鼠标拖动选择功能
2014/03/06 Javascript
将form表单中的元素转换成对象的方法适用表单提交
2014/05/02 Javascript
js控制输入框获得和失去焦点时状态显示的方法
2015/01/30 Javascript
JavaScript中数组的合并以及排序实现示例
2015/10/24 Javascript
20行js代码实现的贪吃蛇小游戏
2017/06/20 Javascript
vue如何获取点击事件源的方法
2017/08/10 Javascript
微信小程序基于本地缓存实现点赞功能的方法
2017/12/18 Javascript
Vue的路由动态重定向和导航守卫实例
2018/03/17 Javascript
快速搭建vue2.0+boostrap项目的方法
2018/04/09 Javascript
JavaScript创建对象方法实例小结
2018/09/03 Javascript
python中字典dict常用操作方法实例总结
2015/04/04 Python
Python解析树及树的遍历
2016/02/03 Python
Python实现Mysql数据统计及numpy统计函数
2019/07/15 Python
使用Python和Scribus创建一个RGB立方体的方法
2019/07/17 Python
django之自定义软删除Model的方法
2019/08/14 Python
浅析几个CSS3常用功能的写法
2014/06/05 HTML / CSS
有影响力的人、名人和艺术家的官方商品:Represent
2019/11/26 全球购物
通信工程毕业生求职信
2013/11/16 职场文书
车辆安全检查制度
2014/01/12 职场文书
我们的节日端午节活动方案
2014/03/02 职场文书
技校毕业生自荐信
2014/06/03 职场文书
幼儿园老师新年寄语2015
2014/12/08 职场文书
创业计划书详解
2019/07/19 职场文书
如何在centos上使用yum安装rabbitmq-server
2021/03/31 Servers
Redis入门教程详解
2021/08/30 Redis
Python机器学习实战之k-近邻算法的实现
2021/11/27 Python