人妖在线一区,国产日韩欧美一区二区综合在线,国产啪精品视频网站免费,欧美内射深插日本少妇

新聞動(dòng)態(tài)

python基礎(chǔ)之類方法和靜態(tài)方法

發(fā)布日期:2021-12-20 21:55 | 文章來源:源碼之家

類方法

class People:
 country='China'
 # 類方法 用classmethod來修飾
 @classmethod  #通過標(biāo)識(shí)符來表示下方方法為類方法
 def get_country(cls):  #習(xí)慣性使用cls
  return cls.country  #訪問類屬性
  pass
 pass
print(People.get_country())  #通過類對(duì)象去引用
p=People()
print('實(shí)例對(duì)象訪問%s'%p.get_country())  #通過實(shí)例對(duì)象去訪問

class People:
 country='China'
 # 類方法 用classmethod來修飾
 @classmethod  #通過標(biāo)識(shí)符來表示下方方法為類方法
 def get_country(cls):  #習(xí)慣性使用cls
  return cls.country  #訪問類屬性
  pass
 @classmethod
 def change_country(cls,data):
  cls.country=data  #修改類屬性的值在類方法中
 pass
print(People.get_country())  #通過類對(duì)象去引用
p=People()
print('實(shí)例對(duì)象訪問%s'%p.get_country())
People.change_country('英')
print(People.get_country())

靜態(tài)方法

class People:
 country='China'
 # 類方法 用classmethod來修飾
 @classmethod  #通過標(biāo)識(shí)符來表示下方方法為類方法
 def get_country(cls):  #習(xí)慣性使用cls
  return cls.country  #訪問類屬性
  pass
 @classmethod
 def change_country(cls,data):
  cls.country=data  #修改類屬性的值在類方法中
 pass
 @staticmethod
 def getData():  #無需傳參數(shù)
  return People.country
 pass
print(People.getData())#可以訪問
# print(People.get_country())  #通過類對(duì)象去引用
p=People()
print(People.getData())#可以訪問  注意 一般情況下 我們不會(huì)通過實(shí)例對(duì)象去訪問靜態(tài)方法

為什么要使用靜態(tài)方法呢?
由于靜態(tài)方法主要來存放邏輯性的代碼 本身和類以及實(shí)例對(duì)象沒有交互
也就是說 在靜態(tài)方法中 不會(huì)涉及到類中方法和屬性的操作
數(shù)據(jù)資源能夠得到有效的充分利用

# demo 返回當(dāng)前的系統(tǒng)時(shí)間
import time #引入時(shí)間模塊
class TimeTest:
 def __init__(self,hour,min,second):
  self.hour=hour
  self.min=min
  self.second=second
 @staticmethod  #直接定義為靜態(tài)方法 不需要實(shí)例屬性
 def showtime():
  return time.strftime('%H:%M:%S',time.localtime())
 pass
print(TimeTest.showtime())
t=TimeTest(2,10,15)
print(t.showtime())  #無必要 直接使用靜態(tài)方法 輸出仍是導(dǎo)入時(shí)間




復(fù)習(xí)


總結(jié)

本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注本站的更多內(nèi)容!

版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。

相關(guān)文章

實(shí)時(shí)開通

自選配置、實(shí)時(shí)開通

免備案

全球線路精選!

全天候客戶服務(wù)

7x24全年不間斷在線

專屬顧問服務(wù)

1對(duì)1客戶咨詢顧問

在線
客服

在線客服:7*24小時(shí)在線

客服
熱線

400-630-3752
7*24小時(shí)客服服務(wù)熱線

關(guān)注
微信

關(guān)注官方微信
頂部