类的重写,如子类中调用父类内函数,如内容达不到要求可以直接在子类中重写该函数,执行后子类内容自动覆盖父类内容。
class struct2(object):
name = 'liuqin'
age = 18
def __init__(self):
print ('my name is {0}'.format(self.name))
def get_name(self):
print ('Repeat my name is {0}'.format(self.name))
def get_age(self):
print ('And I told you my age is {0}'.format(self.age))
class struct1(struct2):
age = 2013
def __init__(self,sunlight,cloud):
self.sunlight=sunlight
self.cloud=cloud
def feel(self):
print ('Now I can see the {0} and touch the {1}'.format(self.sunlight,self.cloud))
def get_age(self):
print ('hahahahhaha')
bb = struct1(sunlight='sunlight',cloud='cloud')
bb.feel()
bb.get_name()
bb.get_age()
结果:
C:\Python27\python.exe E:/untitled/class/class2.py my favourite is snow and rain Repeat my name is liuqin hahahahhaha Process finished with exit code 0
如图子类内重写get_age()输出内容以子类为准,并且调用get_name()时子类中不存在,所以在父类中调用。
补充一般情况下,使用__init__定义的变量,只能在本类中执行,并不能被继承。
如果想使用父类中的init变量需要使用super函数:
父类定义:
class struct2(object): name = 'liuqin' age = 18 def __init__(self,snow,rain): self.snow = snow self.rain = rain print ('my favourite is {0} and {1}'.format(self.snow,self.rain)) def get_name(self): print ('Repeat my name is {0}'.format(self.name)) def get_age(self): print ('And I told you my age is {0}'.format(self.age)) return self.age
子类继承:
class struct1(struct2): age = 2013 def __init__(self,snow,rain): super(struct1, self).__init__(snow, rain) def get_age(self): super(struct1,self).get_age() print ('hahahahhaha')
结果:
C:\Python27\python.exe E:/untitled/class/class2.py my favourite is snow and rain Repeat my name is liuqin And I told you my age is 2013 hahahahhaha Process finished with exit code 0
注意super使用格式:
调用init时: super(子类,self).__init__(父类变量1,父类变量2,等(根据实际变量个数))
调用普通函数时: super(子类,self).函数名称
类的私有变量
如果想定义一些变量只能在class中使用,一些变量可以在实例化中调用需要注意命名方式:
class personal(object): _name='qinlei' __age= 20 def test(self): print (self._name) print (self.__age) aa = personal() aa.test() print (aa._name)
C:\Python27\python.exe E:/untitled/class/class2.py qinlei 20 qinlei Process finished with exit code 0
如图中的命名方式 _+名称表示既可以在class中使用又可以在实例化中调用。
__+名称则只能在class中使用如果在实例化中则会出现错误。
当然如果必须调用该参数需要创建函数:
def get_age(self): return self.__age
C:\Python27\python.exe E:/untitled/class/class2.py qinlei 20 qinlei 20 Process finished with exit code 0
浙公网安备 33010602011771号