python涓疄渚嬫柟娉曪紝绫绘柟娉曪紝闈欐€佹柟娉曠殑鍖哄埆
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python涓疄渚嬫柟娉曪紝绫绘柟娉曪紝闈欐€佹柟娉曠殑鍖哄埆相关的知识,希望对你有一定的参考价值。
鏍囩锛?a href='http://www.mamicode.com/so/1/%e5%ae%9e%e4%be%8b%e5%8c%96' title='瀹炰緥鍖?>瀹炰緥鍖?/a> 榄旀湳鏂规硶 localtime assm second get cal cme 浠g爜
Python涓嚦灏戞湁涓夌姣旇緝甯歌鐨勬柟娉曠被鍨嬶紝鍗冲疄渚嬫柟娉曪紝绫绘柟娉曘€侀潤鎬佹柟娉曘€傚畠浠槸濡備綍瀹氫箟鐨勫憿锛熷浣曡皟鐢ㄧ殑鍛紵瀹冧滑鍙堟湁浣曞尯鍒拰浣滅敤鍛紵涓旂湅涓嬫枃銆?/p>
棣栧厛锛岃繖涓夌鏂规硶閮藉畾涔夊湪绫讳腑銆備笅闈㈡垜鍏堢畝鍗曡涓€涓嬫€庝箞瀹氫箟鍜岃皟鐢ㄧ殑銆傦紙PS锛氬疄渚嬪璞$殑鏉冮檺鏈€澶с€傦級
瀹炰緥鏂规硶
瀹氫箟锛氱涓€涓弬鏁板繀椤绘槸瀹炰緥瀵硅薄锛岃鍙傛暟鍚嶄竴鑸害瀹氫负“self”锛岄€氳繃瀹冩潵浼犻€掑疄渚嬬殑灞炴€у拰鏂规硶锛堜篃鍙互浼犵被鐨勫睘鎬у拰鏂规硶锛夛紱
璋冪敤锛氬彧鑳界敱瀹炰緥瀵硅薄璋冪敤銆?/p>
绫绘柟娉?/strong>
瀹氫箟锛氫娇鐢ㄨ楗板櫒@classmethod銆傜涓€涓弬鏁板繀椤绘槸褰撳墠绫诲璞★紝璇ュ弬鏁板悕涓€鑸害瀹氫负“cls”锛岄€氳繃瀹冩潵浼犻€掔被鐨勫睘鎬у拰鏂规硶锛堜笉鑳戒紶瀹炰緥鐨勫睘鎬у拰鏂规硶锛夛紱
璋冪敤锛氬疄渚嬪璞″拰绫诲璞¢兘鍙互璋冪敤銆?/p>
闈欐€佹柟娉?/strong>
瀹氫箟锛氫娇鐢ㄨ楗板櫒@staticmethod銆傚弬鏁伴殢鎰忥紝娌℃湁“self”鍜?ldquo;cls”鍙傛暟锛屼絾鏄柟娉曚綋涓笉鑳戒娇鐢ㄧ被鎴栧疄渚嬬殑浠讳綍灞炴€у拰鏂规硶锛?/p>
璋冪敤锛氬疄渚嬪璞″拰绫诲璞¢兘鍙互璋冪敤銆?/p>
瀹炰緥鏂规硶
绠€鑰岃█涔嬶紝瀹炰緥鏂规硶灏辨槸绫荤殑瀹炰緥鑳藉浣跨敤鐨勬柟娉曘€傝繖閲屼笉鍋氳繃澶氳В閲娿€?/p>
绫绘柟娉?/h1>
浣跨敤瑁呴グ鍣ˊclassmethod銆?/p>
鍘熷垯涓婏紝绫绘柟娉曟槸灏嗙被鏈韩浣滀负瀵硅薄杩涜鎿嶄綔鐨勬柟娉曘€傚亣璁炬湁涓柟娉曪紝涓旇繖涓柟娉曞湪閫昏緫涓婇噰鐢ㄧ被鏈韩浣滀负瀵硅薄鏉ヨ皟鐢ㄦ洿鍚堢悊锛岄偅涔堣繖涓柟娉曞氨鍙互瀹氫箟涓虹被鏂规硶銆傚彟澶栵紝濡傛灉闇€瑕佺户鎵匡紝涔熷彲浠ュ畾涔変负绫绘柟娉曘€?/p>
濡備笅鍦烘櫙锛?/p>
鍋囪鎴戞湁涓€涓鐢熺被鍜屼竴涓彮绾х被锛屾兂瑕佸疄鐜扮殑鍔熻兘涓猴細
鎵ц鐝骇浜烘暟澧炲姞鐨勬搷浣溿€佽幏寰楃彮绾х殑鎬讳汉鏁帮紱
瀛︾敓绫荤户鎵胯嚜鐝骇绫伙紝姣忓疄渚嬪寲涓€涓鐢燂紝鐝骇浜烘暟閮借兘澧炲姞锛?br /> 鏈€鍚庯紝鎴戞兂瀹氫箟涓€浜涘鐢燂紝鑾峰緱鐝骇涓殑鎬讳汉鏁般€?/p>
鎬濊€?/strong>锛氳繖涓棶棰樼敤绫绘柟娉曞仛姣旇緝鍚堥€傦紝涓轰粈涔堬紵鍥犱负鎴戝疄渚嬪寲鐨勬槸瀛︾敓锛屼絾鏄鏋滄垜浠庡鐢熻繖涓€涓疄渚嬩腑鑾峰緱鐝骇鎬讳汉鏁帮紝鍦ㄩ€昏緫涓婃樉鐒舵槸涓嶅悎鐞嗙殑銆傚悓鏃讹紝濡傛灉鎯宠鑾峰緱鐝骇鎬讳汉鏁帮紝濡傛灉鐢熸垚涓€涓彮绾х殑瀹炰緥涔熸槸娌℃湁蹇呰鐨勩€?/p>
浣跨敤瑁呴グ鍣ˊstaticmethod銆?/p>
闈欐€佹柟娉曟槸绫讳腑鐨勫嚱鏁帮紝涓嶉渶瑕佸疄渚嬨€傞潤鎬佹柟娉曚富瑕佹槸鐢ㄦ潵瀛樻斁閫昏緫鎬х殑浠g爜锛岄€昏緫涓婂睘浜庣被锛屼絾鏄拰绫绘湰韬病鏈夊叧绯伙紝涔熷氨鏄鍦ㄩ潤鎬佹柟娉曚腑锛屼笉浼氭秹鍙婂埌绫讳腑鐨勫睘鎬у拰鏂规硶鐨勬搷浣溿€傚彲浠ョ悊瑙d负锛岄潤鎬佹柟娉曟槸涓?strong>鐙珛鐨勩€佸崟绾殑class ClassTest(object):
__num = 0
@classmethod
def addNum(cls):
cls.__num += 1
@classmethod
def getNum(cls):
return cls.__num
# 杩欓噷鎴戠敤鍒伴瓟鏈柟娉昣_new__锛屼富瑕佹槸涓轰簡鍦ㄥ垱寤哄疄渚嬬殑鏃跺€欒皟鐢ㄧ疮鍔犳柟娉曘€? def __new__(self):
ClassTest.addNum()
return super(ClassTest, self).__new__(self)
class Student(ClassTest):
def __init__(self):
self.name = 鈥樷€?
a = Student()
b = Student()
print(ClassTest.getNum())
闈欐€佹柟娉?/h1>
璀锛屾垜鎯冲畾涔変竴涓叧浜庢椂闂存搷浣滅殑绫伙紝鍏朵腑鏈変竴涓幏鍙栧綋鍓嶆椂闂寸殑鍑芥暟銆?/p>
import time class TimeTest(object): def __init__(self, hour, minute, second): self.hour = hour self.minute = minute self.second = second @staticmethod def showTime(): return time.strftime("%H:%M:%S", time.localtime()) print(TimeTest.showTime()) t = TimeTest(2, 10, 10) nowTime = t.showTime() print(nowTime)
濡備笂锛屼娇鐢ㄤ簡闈欐€佹柟娉曪紙鍑芥暟锛夛紝鐒惰€屾柟娉曚綋涓苟娌′娇鐢紙涔熶笉鑳戒娇鐢級绫绘垨瀹炰緥鐨勫睘鎬э紙鎴栨柟娉曪級銆傝嫢瑕佽幏寰楀綋鍓嶆椂闂寸殑瀛楃涓叉椂锛屽苟涓嶄竴瀹氶渶瑕佸疄渚嬪寲瀵硅薄锛屾鏃跺浜庨潤鎬佹柟娉曡€岃█锛屾墍鍦ㄧ被鏇村儚鏄竴绉嶅悕绉扮┖闂淬€?/p>
鍏跺疄锛屾垜浠篃鍙互鍦ㄧ被澶栭潰鍐欎竴涓悓鏍风殑鍑芥暟鏉ュ仛杩欎簺浜嬶紝浣嗘槸杩欐牱鍋氬氨鎵撲贡浜嗛€昏緫鍏崇郴锛屼篃浼氬鑷翠互鍚庝唬鐮佺淮鎶ゅ洶闅俱€?/p>
浠ヤ笂灏辨槸鎴戝Python鐨勫疄渚嬫柟娉曪紝绫绘柟娉曞拰闈欐€佹柟娉曚箣闂寸殑鍖哄埆鍜屼綔鐢ㄧ殑绠€瑕侀槓杩般€?/p>
以上是关于python涓疄渚嬫柟娉曪紝绫绘柟娉曪紝闈欐€佹柟娉曠殑鍖哄埆的主要内容,如果未能解决你的问题,请参考以下文章