Python中子类的创建
2016-10-14 12:10
253 查看
靠继承来进行子类化是创建和定制新类类型的一种方式,新的类将保持已存在类所有的特性,
而不会改动原来类的定义(指对新类的改动不会影响到原来的类,译者注)。对于新的类类型来说,
这个新的子类可以定制只属于它的特定功能。除了与父类或基类的关系外,子类与通常的类没有什
么区别,也像一般类一样进行实例化。注意下面,子类声明中提到了父类:
运行结果是:
在上面的程序中我们创建了子类B,B继承了基类A的属性和方法。
如果需要,每个子类最好定义它自己的构造器,不然,基类的构造器会被调用。然而如果子类重写构造器,基类的构造器就不会被调用了,这样的话基类的构造其必须被显示的写出来才会被调用,就像程序中写的那样,其中super()方法的使用可以参考我的文章Python中super()方法的使用。
而不会改动原来类的定义(指对新类的改动不会影响到原来的类,译者注)。对于新的类类型来说,
这个新的子类可以定制只属于它的特定功能。除了与父类或基类的关系外,子类与通常的类没有什
么区别,也像一般类一样进行实例化。注意下面,子类声明中提到了父类:
#!/usr/bin/env python class A(object): def __init__(self,nm,ph): self.name = nm self.phone = ph print 'the name of the instance is %s' % self.name print 'the name is %s' % self.name print 'the phonenumber is %s' % self.phone def updatephone(self,newph): self.phone = newph print 'update the instance of %s' % self.name print 'the update phonenumber is %s' % self.phone class B(A): def __init__(self,nm,ph,em,id): # A.__init__(self,nm,ph) super(B,self).__init__(nm,ph) self.email = em self.empid = id print 'the email is %s' % self.email print 'the empid is %s' % self.empid def UpdateEmail(self,em): self.email = em print 'the update email is %s' % self.email a=A('jack','18811223344') a.updatephone('88888888888') b=B('mike','99999999999','mike@mux.com','20160811') b.UpdateEmail('mike@eas.com')
运行结果是:
the name of the instance is jack the name is jack the phonenumber is 18811223344 update the instance of jack the update phonenumber is 88888888888 the name of the instance is mike the name is mike the phonenumber is 99999999999 the email is mike@mux.com the empid is 20160811 the update email is mike@eas.com
在上面的程序中我们创建了子类B,B继承了基类A的属性和方法。
如果需要,每个子类最好定义它自己的构造器,不然,基类的构造器会被调用。然而如果子类重写构造器,基类的构造器就不会被调用了,这样的话基类的构造其必须被显示的写出来才会被调用,就像程序中写的那样,其中super()方法的使用可以参考我的文章Python中super()方法的使用。
相关文章推荐
- Python中线程的创建方法:派生Thread子类
- python学习笔记2-强大的动态创建
- IronPython for ASP.NET:使用IronPython创建一个简单的Web页面
- python下的web开发框架-Django,创建项目
- Python--- subprocess 创建子进程
- 《GOF设计模式》—单件(Singleton)—Delphi源码示例:创建Singleton类的子类(重载Instance方法)
- 创建Python Egg
- Python笔记(二)文本的创建和读取
- Python学习笔记之一 文本文件的创建与显示
- Python模块学习 ---- subprocess 创建子进程
- 子类的创建及初始化过程_Thinking in Java(4)_读书笔记(1)
- python 调用windowsAPI创建应用程序
- 如何创建TextWriter的子类
- 请教各位老师关于:Python 类和对象创建撤销问题 (Python2.5.2,linux)
- Host Python In your Application with IronPython2.0.1 (一): 创建交互环境
- 使用 Python 创建 UNIX 命令行工具
- python 创建xml
- 为Python创建扩展,使python能实现内存共享
- Python学习笔记九:列表(1)--列表元素介绍及创建方法
- 《GOF设计模式》—单件(Singleton)—Delphi源码示例:创建Singleton类的子类(使用环境变量)