python创建子类的方法分析

yipeiwu_com5年前Python基础

本文实例讲述了python创建子类的方法。分享给大家供大家参考,具体如下:

如果你的类没有从任何祖先类派生,可以使用object作为父类的名字。经典类的声明唯一不同之处在于其没有从祖先类派生---此时,没有圆括号:

# !/usr/bin/env python
# -*- coding: utf-8 -*-
class ClassicClassWithoutSuperclasses:
  def fun1(self):
    print 'aaaaaaa'
a=ClassicClassWithoutSuperclasses()
print a
print type(a)
print a.fun1()


C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/eeeee/a5.py
<__main__.ClassicClassWithoutSuperclasses instance at 0x0047BDF0>
<type 'instance'>
aaaaaaa
None

至此,我们已经看到了一些类和子类的例子,下面还有一个简单的例子:

class Parent(object): # define parent class 定义父类
 def parentMethod(self):
  print 'calling parent method


# !/usr/bin/env python
# -*- coding: utf-8 -*-
class Parent(object): # define parent class 定义父类
 def parentMethod(self):
  print 'calling parent method'
class Child(Parent): # define child class 定义子类
 def childMethod(self):
  print 'calling child method'
a=Parent() # instance of parent 父类的实例
print a.parentMethod()

C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/eeeee/a5.py
calling parent method
None

>>> c = Child() # instance of child 子类的实例
>>> c.childMethod() # child calls its method 子类调用它的方法
calling child method
>>> c.parentMethod() # calls parent's method 调用父类的方法
calling parent method

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

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

相关文章

Python实现GUI学生信息管理系统

Python实现GUI学生信息管理系统

本文实例为大家分享了Python实现GUI学生信息管理系统的具体代码,供大家参考,具体内容如下 项目环境:  软件环境:     &n...

django模板语法学习之include示例详解

前言 在很多网站中,基本上的都会有一个开头和一个结尾,在每一个网页中都会显示。相对于这种的来说,在Django中,最好的方法就是使用include的标签,在每一个模板中都加入这个开头和结...

django 按时间范围查询数据库实例代码

从前台中获得时间范围,在django后台处理request中数据,完成format,按照范围调用函数查询数据库。 介绍一个简单的功能,就是从web表单里获取用户指定的时间范围,然后在数据...

如何使用python3获取当前路径及os.path.dirname的使用

这篇文章主要介绍了如何使用python3获取当前路径及os.path.dirname的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考...

Python 实现OpenCV格式和PIL.Image格式互转

OpenCV转换成PIL.Image格式: import cv2 from PIL import Image import numpy img = cv2.imread("...