Python3.x:定義一個類而且調用

Python3.x:定義一個類而且調用

1,定一個類Shrjj(其中有屬性:name, jjzt,fbsjj,etf,lof,fjlof):app

class Shrjj(object):
    
    def __init__(self, name, jjzt,fbsjj,etf,lof,fjlof):
        self.name = name
        self.jjzt = jjzt
        self.fbsjj = fbsjj
        self.etf = etf
        self.lof = lof
        self.fjlof = fjlof

    def __get__(self, instance, cls):
        if instance is None:
            return self
        else:
            return instance.__dict__[self.name]

    def __set__(self, instance, value):
        instance.__dict__[self.name] = value

    def __delete__(self, instance):
        del instance.__dict__[self.name]

2,調用Shrjj類:  函數

# 測試
if __name__ == '__main__':
    lisrt = []
    # 實例化Shrjj類
    p = Shrjj('測試','5','4','3','2','1')
    p2 = Shrjj('測試2','52','4','3','2','12')
    lisrt.append(p)
    lisrt.append(p2)
    # 定義空類(必須帶參數,不能寫成:p3=Shrjj())
    p3 = Shrjj('','','','','','')
    # 給類屬性賦值
    p3.name = "cesaldasd"
    p3.jjzt ="3232.23"
    lisrt.append(p3)

    print(lisrt[2].name)

3,運行結果:測試

cesaldasd

 4,能夠定義可變參數類(參數個數不固定):spa

class People(object):
    #構造函數,不明肯定義參數個數
    def __init__(self, *args):
        self.args = args

    def sayAge(self):
        print(str(self.args))
#調用方式
p1 = People()
p2 = People('charlie')
p3 = People('charlie', 22)

p1.sayAge()
p2.sayAge()
p3.sayAge()
相關文章
相關標籤/搜索