您的位置:首页 > 编程语言 > Python开发

Python中子类的创建

2016-10-14 12:10 253 查看
靠继承来进行子类化是创建和定制新类类型的一种方式,新的类将保持已存在类所有的特性,

而不会改动原来类的定义(指对新类的改动不会影响到原来的类,译者注)。对于新的类类型来说,

这个新的子类可以定制只属于它的特定功能。除了与父类或基类的关系外,子类与通常的类没有什

么区别,也像一般类一样进行实例化。注意下面,子类声明中提到了父类:

#!/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()方法的使用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息