PHP前端开发

python中继承有什么用法?

百变鹏仔 3小时前 #Python
文章标签 有什么

本篇文章给大家带来的内容是关于python中继承有什么用法?python继承的用法详解,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

面向对象三大特征
   1.封装:根据职责将属性和方法封装到一个抽象的类中
   2.继承:实现代码的重用,相同的代码不需要重复的写
   3.多态
单继承
继承的概念:子类拥有父类的所有属性和方法
继承的语法
class 类名(父类):
    def 子类特有的方法
"""
"""
cat类是animal类的子类,animal类是cat类的父类,cat从animal类继承
cat类是animal类的派生类,animal类是cat类的基类,cat类从animal类派生
"""
1.

class Animal(object):    def eat(self):        print '吃'    def drink(self):        print '喝'    def run(self):        print '跑'    def sleep(self):        print '睡'
class Cat(Animal):    # 子类拥有父类的所有属性和方法    def call(self):        print '喵喵'class Dog(Animal):    def bark(self):        print '旺旺'class Hellokitty(Cat):    def speak(self):        print '我可以说日语'
# 创建一个猫对象fentiao = Cat()fentiao.eat()fentiao.drink()fentiao.run()fentiao.sleep()fentiao.call()

2.
重写父类方法
    1.覆盖父类的方法
    2.扩展父类的方法
"""

class Animal:    def eat(self):        print '吃'    def drink(self):        print '喝'    def run(self):        print '跑'    def sleep(self):        print '睡'
class Cat(Animal):    # 子类拥有父类的所有属性和方法    def call(self):        print '喵喵'
class Hellokitty(Cat):    def speak(self):        print '我可以说日语'    def call(self):        # 针对子类特有的需求,编写代码        print '欧哈有~空你起哇'        # 调用原本在父类中封装的代码        Cat.call(self)        # 增加其他的子类代码        print '#!@$@!#!#'kt = Hellokitty()# 如果子类中,重写了父类的方法# 在运行中,只会调用在子类中重写的父类的方法而不会调用父类的方法kt.call()

3.

class Bird:    def __init__(self):        self.hungry = True    # 鸟吃过了以后就不饿了    def eat(self):        if self.hungry:            print 'Aaaaahhh...'            self.hungry = False        else:            print 'No thanks'
class SongBird(Bird):    def __init__(self):        self.sound = 'Squawk!'        Bird.__init__(self)    def sing(self):        print self.sound
littlebird = SongBird()littlebird.eat()littlebird.sing()

4.

class A:    def test(self):        print 'A-----test 方法'    def demo(self):        print 'A-----demo 方法'class B:    def test(self):        print 'B------test 方法'    def demo(self):        print 'B-------demo方法'class C(B,A):    """多继承可以让子类对象,同时具有多个父类的属性和方法"""    pass
# 创建子类对象c = C()c.test()c.demo()