类--子类VS父类(一)
程序员文章站
2022-05-29 09:42:19
...
子类和父类的关系是怎么样的呢,具体的用法是什么样的呢?
让我们通过下面的例子来了解下:
#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’
所以,从上面可以看出,子类可以调用父类里面的所有变量和方法,同样不可以直接通过实例和子类本身去调用私有方法和私有变量;