类--子类VS父类(一)

子类和父类的关系是怎么样的呢,具体的用法是什么样的呢?
让我们通过下面的例子来了解下:

#encoding=utf-8

class Animal:
    """hello kitty"""
    count=0
    def __init__(self,name):
        self.name=name
        Animal.count+=1
        self.__feather=True

    def getName(self):
        return self.name

    def get_count(self):
        return Animal.count

    def get_feather(self):
        print self.__get_feather()
        return self.__feather

    def __get_feather(self):
        return "feather"

    def set_feather(self,value):
        if value not in [True,False]:
            return 'value is not vaild !'
        else:
            self.__feather=value
            return self.__feather


    @classmethod
    #类方法,只有在Animal里面才可以用
    def print_doc(cls,x):
        cls.x=x
        print cls.x
        return cls.__doc__

    @staticmethod
    def print_module(y):
        print y
        return Animal.__module__


class Cat(Animal):
    def __init__(self,age):
        Animal.__init__(self,'ajin')#注意这里必须要给数值而不是变量名
        self.age=age

    def get_age(self):
        return self.age

c=Cat(2)
print c.get_age()
print c.getName()
print c.get_feather()
print c.print_doc(666)
print c.print_module(777)
#判断c是谁的实例
print isinstance(c,Animal)
print isinstance(c,Cat)

这里写图片描述

print c.__get_feather()

报错:AttributeError: Cat instance has no attribute ‘__get_feather’

所以,从上面可以看出,子类可以调用父类里面的所有变量和方法,同样不可以直接通过实例和子类本身去调用私有方法和私有变量;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值