设为首页 加入收藏

TOP

Python——继承(二)
2019-08-04 00:19:38 】 浏览:75
Tags:Python 继承
ment>) | super(type) -> unbound super object | super(type, obj) -> bound super object; requires isinstance(obj, type) | super(type, type2) -> bound super object; requires issubclass(type2, type) | Typical use to call a cooperative superclass method: | class C(B): | def meth(self, arg): | super().meth(arg) | This works for class methods too: | class C(B): | @classmethod | def cmeth(cls, arg): | super().cmeth(arg) ...

通过帮助信息,可以看到,当调用父类的实例方法时,会自动绑定第一个参数self;当调用类方法时,会自动绑定第一个参数cls。

接下来修改上面的程序:

class Animal:
    def __init__(self,pet,name):
        self.pet = pet
        self.name = name
        
    def favourite_animal(self):
        print ('我有一只%s,他叫%s!'%(self.pet,self.name))

class Fruit:
    def __init__(self,kind):
        self.kind = kind
        
    def favourite_fruit(self):
        print ('我喜欢的水果是%s!'%self.kind)


class Myself(Animal,Fruit):
    def __init__(self,pet,name,kind):
        Fruit.__init__(self,kind)   # 通过未绑定方法调用父类构造方法
        super().__init__(pet,name)  # 通过super()函数调用父类构造方法
        
        
               

M = Myself('狗','大黄','苹果')
M.favourite_animal()    # 打印 我有一只狗,他叫大黄!
M.favourite_fruit()     # 打印 我喜欢的水果是苹果!

  

 

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇零基础怎么学Python?6个月的学习.. 下一篇Python爬虫框架

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目