最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時(shí)間:2021年10月24日 14:59:59   作者:qianqqqq_lu  
這篇文章主要介紹了python類方法和靜態(tài)方法,實(shí)例分析了Python中返回一個(gè)返回值與多個(gè)返回值的方法,需要的朋友可以參考下

類方法

在這里插入圖片描述

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

在這里插入圖片描述

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

在這里插入圖片描述

靜態(tài)方法

在這里插入圖片描述

class People:
    country='China'
    # 類方法 用classmethod來修飾
    @classmethod  #通過標(biāo)識符來表示下方方法為類方法
    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())  #通過類對象去引用
p=People()
print(People.getData())   #可以訪問  注意 一般情況下 我們不會通過實(shí)例對象去訪問靜態(tài)方法

在這里插入圖片描述

為什么要使用靜態(tài)方法呢?
由于靜態(tài)方法主要來存放邏輯性的代碼 本身和類以及實(shí)例對象沒有交互
也就是說 在靜態(tài)方法中 不會涉及到類中方法和屬性的操作
數(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)容!

相關(guān)文章

最新評論

泸西县| 庐江县| 大荔县| 香港 | 漯河市| 新巴尔虎右旗| 定结县| 马龙县| 镇巴县| 焉耆| 八宿县| 泽普县| 邓州市| 台南县| 铁岭市| 芦山县| 砚山县| 武夷山市| 彩票| 交城县| 建宁县| 五原县| 碌曲县| 珠海市| 洪江市| 鱼台县| 光山县| 莱西市| 泉州市| 巴彦县| 大港区| 布尔津县| 济阳县| 曲沃县| 中西区| 繁峙县| 龙山县| 柳林县| 张家界市| 赣榆县| 改则县|