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

相关文章

C#返回当前系统所有可用驱动器符号的方法

本文实例讲述了C#返回当前系统所有可用驱动器符号的方法。分享给大家供大家参考。具体如下: // The initial C# code for the "plain" WMI que...

django的分页器Paginator 从django中导入类

django的分页器Paginator 从django中导入类

先创建表,然后生成批量数据。 在models文件里 from django.db import models # Create your models here. class...

查看端口并杀进程python脚本代码

我就废话不多说,直接上代码吧: # -*- coding: utf-8 -*- import os out=os.system('netstat -aon|findstr "25"'...

python pandas中DataFrame类型数据操作函数的方法

python数据分析工具pandas中DataFrame和Series作为主要的数据结构. 本文主要是介绍如何对DataFrame数据进行操作并结合一个实例测试操作函数。 1)查看Dat...

对dataframe进行列相加,行相加的实例

实例如下所示: >>> import pandas as pd >>> df = pd.DataFrame({"x":['a','b','c','...