目标:

1.父类,子类定义,以及子类调用父类

2.类的组合使用

3.内置功能


1)父类、子类以及调用父类

脚本内容如下:

#!/usr/bin/env python

# -*- coding: utf-8 -*-


# 父类

class AddBook(object):

    def __init__(self, name, phone):

        self.name = name

        self.phone = phone


    def get_phone(self):

        return self.phone


# 子类,继承

class EmplEmail(AddBook):

    def __init__(self, nm, ph, email):

        # AddBook.__init__(self, nm, ph)          #调用父类方法一

        super(EmplEmail, self).__init__(nm, ph)   #调用父类方法二

        self.email = email


    def get_email(self):

        return self.email


# 调用

if __name__ == "__main__":

    Detian = AddBook('jack', '11223344556')

    Meng = AddBook('lili', '11223344557')


    print Detian.get_phone()

    print AddBook.get_phone(Meng)


    alice = EmplEmail('alice', '11223344558', 'alice@test.com')

    print alice.get_email(), alice.get_phone()


2)类的组合使用

脚本内容如下:

#!/usr/bin/env python

# -*- coding: utf-8 -*-


'''

1.class类的组合使用

2.手机、邮箱、QQ等是可以变化的(定义在一起),姓名不可变(单独定义)。

3.在另一个类中引用

'''


class Info(object):

    def __init__(self, phone, email, qq):

        self.phone = phone

        self.email = email

        self.qq = qq


    def get_phone(self):

        return self.phone


    def update_phone(self, newphone):

        self.phone = newphone

        print "手机号更改已更改"


    def get_email(self):

        return self.email


class AddrBook(object):

    '''docstring for AddBook'''

    def __init__(self, name, phone, email, qq):

        self.name = name

        self.info = Info(phone, email, qq)


if __name__ == "__main__":

    Peng = AddrBook('jack', '11223344556', 'peng@test.com', '123456')

    print Peng.info.get_phone()

    Peng.info.update_phone(11223344559)

    print Peng.info.get_phone()

    print Peng.info.get_email()


3)内置功能(函数()加与不加的区别)

脚本内容如下:

#!/usr/bin/env python

#coding: utf8


class  Book(object):

    def __init__(self,title,author):

  self.title = title

      self.author = author


    def __str__(self):

      return self.title


def __call__(self):

      print "%s is written by %s" % (self.title,self.author)

  

if __name__ == '__main__':

      pybook = Book("Core Python","Wesley")

      print pybook     #因为类中定义了__str__方法,此处打印出的内容是__str__的返回值。

  pybook()      #调用pybook就是执行__call__方法中的代码。