Python面向对象之类的定义与继承用法示例

yipeiwu_com6年前Python基础

本文实例讲述了Python面向对象之类的定义与继承用法。分享给大家供大家参考,具体如下:

定义一个类

类中的方法同,类外方法,默认传self

类的构造函数是  __init__

# -*- coding:utf-8 -*-
class Hello:
  def __init__(self,name):
    self.name=name
   def sayHello(self):
    print ("Hello Python {0}".format(self.name))
h=Hello("Newer")
h.sayHello()

运行结果:

Hello Python Newer

继承

例子:注意父类构造函数和继承格式的书写

# -*- coding:utf-8 -*-
class Hello:
  def __init__(self,name):
    self.name=name
  def sayHello(self):
    print ("Hello Python {0}".format(self.name))
class Hi(Hello):
  def __init__(self,name):
    Hello.__init__(self,name)
  def sayHi(self):
    print ("Hi {0}".format(self.name))
h1=Hi("Newer")
h1.sayHi()

运行结果:

Hi Newer

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

pytorch permute维度转换方法

permute prediction = input.view(bs, self.num_anchors, self.bbox_attrs, in_h, in_w).permut...

python通过wxPython打开一个音频文件并播放的方法

本文实例讲述了python通过wxPython打开一个音频文件并播放的方法。分享给大家供大家参考。具体如下: 这段代码片段使用wx.lib.filebrowsebutton.FileBr...

python中xrange和range的区别

range 函数说明:range([start,] stop[, step]),根据start与stop指定的范围以及step设定的步长,生成一个序列。range示例:复制代码 代码如下...

常见的python正则用法实例讲解

下面列出Python正则表达式的几种匹配用法: 此外,关于正则的一切http://deerchao.net/tutorials/regex/regex.htm  1.测试正则表...

python NumPy ndarray二维数组 按照行列求平均实例

我就废话不多说了,直接上代码吧! c = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10]]) print(c.mean(axi...