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从入门到精通(DAY 1)
Dec 20 Python
Python正则表达式常用函数总结
Jun 24 Python
itchat和matplotlib的结合使用爬取微信信息的实例
Aug 25 Python
对Python实现简单的API接口实例讲解
Dec 10 Python
使用python 打开文件并做匹配处理的实例
Jan 02 Python
详解python执行shell脚本创建用户及相关操作
Apr 11 Python
Python实现九宫格式的朋友圈功能内附“马云”朋友圈
May 07 Python
django框架使用方法详解
Jul 18 Python
python scrapy爬虫代码及填坑
Aug 12 Python
python命令 -u参数用法解析
Oct 24 Python
python 常用日期处理-- datetime 模块的使用
Sep 02 Python
Python threading模块condition原理及运行流程详解
Oct 05 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简单调用函数与类库的方法
2017/03/15 PHP
网页里控制图片大小的相关代码
2006/06/25 Javascript
jquery 学习之二 属性(html()与html(val))
2010/11/25 Javascript
修改jquery.lazyload.js实现页面延迟载入
2010/12/22 Javascript
javascript全局变量封装模块实现代码
2012/11/28 Javascript
JavaScript字符串String和Array操作的有趣方法
2012/12/18 Javascript
通过js获取div的background-image属性
2013/10/15 Javascript
jQuery大于号(>)选择器的作用解释
2015/01/13 Javascript
js实现图片无缝滚动
2015/12/23 Javascript
jQuery事件用法详解
2016/10/06 Javascript
jquery操作ID带有变量的节点实例
2016/12/07 Javascript
jQuery实现动态生成表格并为行绑定单击变色动作的方法
2017/04/17 jQuery
基于js粘贴事件paste简单解析以及遇到的坑
2017/09/07 Javascript
js+html5生成自动排列对话框实例
2017/10/09 Javascript
webpack打包nodejs项目的方法
2018/09/26 NodeJs
详解vue+axios给开发环境和生产环境配置不同的接口地址
2019/08/16 Javascript
python控制台英汉汉英电子词典
2020/04/23 Python
python不换行之end=与逗号的意思及用途
2017/11/21 Python
Python cookbook(数据结构与算法)通过公共键对字典列表排序算法示例
2018/03/15 Python
python调用百度语音识别实现大音频文件语音识别功能
2018/08/30 Python
Numpy之random函数使用学习
2019/01/29 Python
Python 把序列转换为元组的函数tuple方法
2019/06/27 Python
Python 处理文件的几种方式
2019/08/23 Python
Django如何实现防止XSS攻击
2020/10/13 Python
CSS3制作气泡对话框的实例教程
2016/05/10 HTML / CSS
html5开发三八女王节表白神器
2018/03/07 HTML / CSS
Europcar葡萄牙:葡萄牙汽车和货车租赁
2017/10/13 全球购物
物流司机岗位职责
2013/12/28 职场文书
计算机专业毕业生自荐信
2013/12/31 职场文书
函授自我鉴定范文
2014/02/06 职场文书
销售员求职个人的自我评价
2014/02/19 职场文书
投标承诺书怎么写
2014/05/24 职场文书
超市开业庆典活动策划方案
2014/09/15 职场文书
县委务虚会发言材料
2014/10/20 职场文书
2015年元旦文艺晚会总结(学院)
2014/11/28 职场文书
2015商场元旦促销活动策划方案
2014/12/09 职场文书