美文网首页
python 类

python 类

作者: 小姐姐催我改备注 | 来源:发表于2019-02-14 15:37 被阅读0次
    class Mydata(object):
        'creat a class'
        def __init__(self,nm,ph):
            self.name = nm
            self.phone = ph
            print 'creat a new obj!'
    
        def update(self,newph):
            self.phone = newph
            print 'update new obj!'
    wangwentao =Mydata('wangwentao','187****4416')
    hjj = Mydata('hjj','153****1381')
    print wangwentao.name
    print wangwentao.phone
    print hjj.name
    print hjj.phone
    print hjj.update('153****1381_')
    print hjj.phone
    
    class Newid(Mydata):
        def __init__(self,nm,ph,em):
            Mydata.__init__(self,nm,ph)
            self.email = em
    
        def updateemail(self,newem):
            self.email = newem
            print 'update new email!'
    
    wangwentao = Newid('wangwentao','187****4416','187****4416@163.com')
    hjj = Newid('hjj','153****1381','153****1381@163.com')
    print wangwentao.name
    print wangwentao.phone
    print wangwentao.email
    print hjj.name
    print hjj.phone
    print hjj.email
    hjj.updateemail('153****1381_.@163.com')
    print hjj.email
    

    上述代码描述了。首先是创建一个基础类,在这里要注意几点:

    1.

    注意类在刚开始时候需要要初始化,也就是构造函数,在这里定义成员变量。并且进行初始化,

    2.

    如果是基础类的情况下 class mydate(object):,否则就需要用 class Newclass(mydata):这种方式表示继承。

    3.

    在继承的情况下也需要注意,首先我们需要对类进行初始化,然后来添加自己新的成员变量。一般的方式是可以继承父类的初始化
    def init(self,nm,ph,em):
    mydata.init(self,nm,ph)
    这种方式表示继承父类的初始化。

    class P(object):
        def __init__(self):
            print 'creat new P class!'
        def foo(self):
            print 'Hi ,I am P-foo()'
    class C(P):
        def foo(self):
            super(C,self).__init__()
            return 'Hi,I am C-foo()'
    c = C()
    print c.foo()
    

    这里要注意super(C,self).function(),这个是类在继承过程中寻找父类的方法,这样我们就不用知道具体父类的名称,而直接使用父类的方法。

    相关文章

      网友评论

          本文标题:python 类

          本文链接:https://www.haomeiwen.com/subject/lxveeqtx.html