Python3.x:定义一个类并且调用

Python3.x:定义一个类并且调用

1,定一个类Shrjj(其中有属性:name, jjzt,fbsjj,etf,lof,fjlof):

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,可以定义可变参数类(参数个数不固定):

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()
原文地址:https://www.cnblogs.com/lizm166/p/8303231.html