python-面向对象(指数对象举例)

class Index(object):
    def __init__(self,index_name,index_code,closePrice_yesterday,closePrice_today):
        self.index_code=index_code
        self.index_name=index_name
        self.closePrice_yesterday=closePrice_yesterday
        self.closePrice_today=closePrice_today
        
    def display(self):
        print(("%s"+"  "+"%s"+"  "+"%s"+"  "+"%s"+"  "+"%s")% (self.index_name,self.index_code,self.closePrice_yesterday,self.closePrice_today))

    def profit(self):
        index_profit=(self.closePrice_today-self.closePrice_yesterday)/self.closePrice_yesterday
        return index_profit
    

index300=Index("沪深300","000300",5306.59,5064.82)
index50=Index("上 证50","000016",3347.12,3179.65)
index500=Index("中证500","000905",11366.29,10879.84)

print("----------指数收益率计算结果---------------")
print(index300.index_name+"收益率: "+str(index300.profit()*100)+"%")
print(index50.index_name+"收益率: "+str(index50.profit()*100)+"%")
print(index500.index_name+"收益率: "+str(index500.profit()*100)+"%")

输出结果如下:

----------指数收益率计算结果---------------
沪深300收益率: -4.55603315877%
上 证50收益率: -5.00340591314%
中证500收益率: -4.27976059031%
原文地址:https://www.cnblogs.com/nzyjlr/p/4877794.html