python静态方法实例
本文实例讲述了python静态方法。分享给大家供大家参考。
具体实现方法如下:
staticmethodFoundat:__builtin__ staticmethod(function)->method Convertafunctiontobeastaticmethod. Astaticmethoddoesnotreceiveanimplicitfirstargument. Todeclareastaticmethod,usethisidiom: classC: deff(arg1,arg2,...):... f=staticmethod(f) Itcanbecalledeitherontheclass(e.g.C.f())oronan instance (e.g.C().f()). Theinstanceisignoredexceptforitsclass. StaticmethodsinPythonaresimilartothosefoundin JavaorC++. Foramoreadvancedconcept,seetheclassmethodbuiltin. classEmployee: """EmployeeclasswithstaticmethodisCrowded""" numberOfEmployees=0 #numberofEmployeescreated maxEmployees=10 #maximumnumberofcomfortableemployees defisCrowded(): """Staticmethodreturnstrueiftheemployeesarecrowded""" returnEmployee.numberOfEmployees>Employee.maxEmployees #createstaticmethod isCrowded=staticmethod(isCrowded) def__init__(self,firstName,lastName): """Employeeconstructor,takesfirstnameandlastname""" self.first=firstName self.last=lastName Employee.numberOfEmployees+=1 def__del__(self): """Employeedestructor""" Employee.numberOfEmployees-=1 def__str__(self): """StringrepresentationofEmployee""" return"%s%s"%(self.first,self.last) #mainprogram defmain(): answers=["No","Yes"] #responsestoisCrowded employeeList=[] #listofobjectsofclassEmployee #callstaticmethodusingclass print"Employeesarecrowded?", printanswers[Employee.isCrowded()] print"\nCreating11objectsofclassEmployee..." #create11objectsofclassEmployee foriinrange(11): employeeList.append(Employee("John","Doe"+str(i))) #callstaticmethodusingobject print"Employeesarecrowded?", printanswers[employeeList[i].isCrowded()] print"\nRemovingoneemployee..." delemployeeList[0] print"Employeesarecrowded?",answers[Employee.isCrowded()] if__name__=="__main__": main()
希望本文所述对大家的Python程序设计有所帮助。