python类继承用法实例分析
本文实例讲述了python类继承用法。分享给大家供大家参考。具体如下:
help('object')#test
classClass1(object):
"""
Class1inheritsthemostbasiccontainerclassobject(justaplaceholder)
thisisthenewerclasswritingconvention,adding(object)is"still"optional
"""
k=7
def__init__(self,color='green'):
"""
Specialmethod__init__()iscalledfirst(actsasConstructor).
Itbringsindatafromoutsidetheclasslikethevariablecolor.
(inthiscasecolorisalsosettoadefaultvalueofgreen)
Thefirstparameterofanymethod/functionintheclassisalwaysself,
thenameselfisusedbyconvention.Assigningcolortoself.colorallowsit
tobepassedtoallmethodswithintheclass.Thinkofselfasacarrier,
orifyouwantimpressfolkscallittargetinstanceobject.
Thevariablekisassignedavalueintheclass,butoutsideofthemethods.
Youcanaccesskinamethodusingself.k
"""
self.color=color
defHello1(self):
print"HellofromClass1!"
defprintColor(self):
"""inthiscaseselfallowscolortobepassed"""
print"Ilikethecolor",self.color
def__localHello(self):
"""
Avariableorfunctionwithadoubleunderlineprefixandnoormax.single
underlinepostfixisconsideredprivatetotheclassandisnotinheritedor
accessibleoutsidetheclass.
"""
print"AhardyHelloonlyusedwithintheclass!"
classClass2(Class1):
"""
Class2inheritsClass1(Class2isthesubclass,Class1thebaseorsuperclass)
Class1hastobecodedbeforeClass2forthistowork!!!
Class2cannowuseanymethodofClass1,andeventhevariablek
"""
defHello2(self):
print"HellofromClass2!"
printself.k,"ismyfavoritenumber"
#thecolorblueispassedto__init__()
c1=Class1('blue')
#Class2inheritedmethod__init__()fromClass1
#ifyouusedc2=Class2(),thedefaultcolorgreenwouldbepicked
c2=Class2('red')
print'-'*20
print"Class1sayshello:"
c1.Hello1()
print'-'*20
print"Class2saysaClass1hello:"
c2.Hello1()
print'-'*20
print"Class2saysitsownhello:"
c2.Hello2()
print'-'*20
print"Class1colorvia__init__():"
c1.printColor()
print'-'*20
print"Class2colorviainherited__init__()andprintColor():"
c2.printColor()
print'-'*20
print"Class1changesitsmindaboutthecolor:"
c1=Class1('yellow')#sameas:c1.__init__('yellow')
c1.printColor()
print'-'*20
print"WonderwhatClass2hastosaynow:"
c2.printColor()
print'-'*20
#thiswouldgiveanerror!Class1doesnothaveamethodHello2()
ifhasattr(Class1,"Hello2"):
printc1.Hello2()
else:
print"Class1doesnotcontainmethodHello2()"
#checkinheritance
ifissubclass(Class2,Class1):
print"Class2isasubclassofClass1,orClass2hasinheritedClass1"
#youcanaccessvariablekcontainedinClass1
print"VariablekfromClass1=",c1.k
print'-'*20
#thiswouldgiveanerror!Youcannotaccessaclassprivatemethod
ifhasattr(Class1,"__localHello()"):
printc1.__localHello()
else:
print"NoaccesstoClass1privatemethod__localHello()"
运行结果如下:
Helponclassobjectinmodule__builtin__: classobject |Themostbasetype -------------------- Class1sayshello: HellofromClass1! -------------------- Class2saysaClass1hello: HellofromClass1! -------------------- Class2saysitsownhello: HellofromClass2! 7ismyfavoritenumber -------------------- Class1colorvia__init__(): Ilikethecolorblue -------------------- Class2colorviainherited__init__()andprintColor(): Ilikethecolorred -------------------- Class1changesitsmindaboutthecolor: Ilikethecoloryellow -------------------- WonderwhatClass2hastosaynow: Ilikethecolorred -------------------- Class1doesnotcontainmethodHello2() Class2isasubclassofClass1,orClass2hasinheritedClass1 VariablekfromClass1=7 -------------------- NoaccesstoClass1privatemethod__localHello()
希望本文所述对大家的Python程序设计有所帮助。