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程序设计有所帮助。

相关文章

python 实现单通道转3通道

下面有两种方法都可以: import numpy as np a=np.asarray([[10,20],[101,201]]) # a=a[:,:,np.newaxis] # p...

python中 * 的用法详解

1、表示乘号 2、表示倍数,例如: def T(msg,time=1): print((msg+' ')*time) T('hi',3) 打印结果(打印3次): hi h...

python2.7+selenium2实现淘宝滑块自动认证功能

python2.7+selenium2实现淘宝滑块自动认证功能

本文为大家分享了python2.7+selenium2实现淘宝滑块自动认证的具体代码,供大家参考,具体内容如下 1.编译环境 操作系统:win7;语言:python2.7+selen...

对Python闭包与延迟绑定的方法详解

Python闭包可能会在面试或者是工作中经常碰到,而提到Python的延迟绑定,肯定就离不开闭包的理解,今天总结下 关于闭包的概念以及一个延迟绑定的面试题。 Python闭包 1、什么是...

在Python中操作字典之update()方法的使用

 update()方法添加键 - 值对到字典dict2。此函数不返回任何值。 语法 以下是update()方法的语法: dict.update(dict2) 参数...