时间:2021-07-01 10:21:17 帮助过:20人阅读
面向对象三大特征
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.soundlittlebird = 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()
相关推荐:
Python中的单继承与多继承
python类的继承是什么?类的继承有什么样的规则?
以上就是python中继承有什么用法?python继承的用法详解的详细内容,更多请关注Gxl网其它相关文章!