子類和父類的關係是怎麼樣的呢,具體的用法是什麼樣的呢?
讓我們通過下面的例子來了解下:
#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’
所以,從上面可以看出,子類可以調用父類裏面的所有變量和方法,同樣不可以直接通過實例和子類本身去調用私有方法和私有變量;