Python中子类的创建

靠继承来进行子类化是创建和定制新类类型的一种方式,新的类将保持已存在类所有的特性,
而不会改动原来类的定义(指对新类的改动不会影响到原来的类,译者注)。对于新的类类型来说,
这个新的子类可以定制只属于它的特定功能。除了与父类或基类的关系外,子类与通常的类没有什
么区别,也像一般类一样进行实例化。注意下面,子类声明中提到了父类:

#!/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()方法的使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值