1、class的定义

class X(Y)
"Make a class named X that is-a Y."
class X(object): def __init__(self, J)
"class X has-a __init__ that takes self and J parameters."
class X(object): def M(self, J)
"class X has-a function named M that takes self and J parameters."
foo = X()
"Set foo to an instance of class X."
foo.M(J)
"From foo get the M function, and call it with parameters self, J."
foo.K = Q
"From foo get the K attribute and set it to Q."

In each of these where you see X, Y, M, J, K, Q, and foo you can treat those like blank spots. For example, I can also write these sentences as follows:

  1. "Make a class named ??? that is-a Y."
  2. "class ??? has-a __init__ that takes self and ??? parameters."
  3. "class ??? has-a function named ??? that takes self and ??? parameters."
  4. "Set foo to an instance of class ???."
  5. "From foo get the ??? function, and call it with self=??? and parameters ???."
  6. "From foo get the ??? attribute and set it to ???."
# 例:类的概念 
class 人类: 
             名字 = '未命名' # 成员变量 
 def 说话(内容): # 成员函数 
                print 内容                 # 成员变量赋初始值 
 
 
某人 = 人类()               # 定义一个人类对象某人 
某人.名字 = "路人甲" 
某人.说话      ('大家好') # 路人甲说话 
>>> 大家好!                  # 输出
# 例:类定义及使用 
class CAnimal: 
              name = 'unname' # 成员变量 
    def __init__(self,voice='hello'):        # 重载构造函数 
         self.voice = voice                       # 创建成员变量并赋初始值 
    def __del__(self):               # 重载析构函数 
         pass                             # 空操作 
    def Say(self): 
            print self.voice 
 
 
t = CAnimal()              # 定义动物对象t 
t.Say()              # t说话 
>> hello                   # 输出 
dog = CAnimal('wow')      # 定义动物对象dog 
dog.Say()                  # dog说话 
>> wow                   # 输出

import random

class Die(object):
    '''Simulate a 6-sided die.'''
    def roll(self):
        self.value = random.randint(0,5)
        return self.value
    def getValue(self):
        return self.value

In this case, the private instance variable, value,will have a value in the range 0 \leq value < 5. When getValue()adds 1, the value is in the usual range for a single die,1 \leq value < 6.


2、实际使用

# 例:类的继承 
class CAnimal: 
        def __init__(self,voice='hello'): # voice初始化默认为hello 
              self.voice = voice 
        def Say(self): 
            print self.voice 
  def Run(self): 
            pass     # 空操作语句(不做任何操作) 
 
 
class CDog(CAnimal):        # 继承类CAnimal 
    def SetVoice(self,voice): # 子类增加函数
          SetVoice
        self.voice = voice 
       def Run(self,voice): # 子类重载函数Run
           
            print 'Running' 
 
 
bobo = CDog() 
bobo.SetVoice('My Name is BoBo!')      # 设置child.data为hello 
bobo.Say() 
bobo.Run() 
>> My Name is BoBo! 
>> Running

class CAnimal:
    def __init__(self,voice='hello'):
        name = 'unname'
        self.voice = voice
    
    def Say(self):
        print self.voice
    def Run(self):
        pass
    
class CDog(CAnimal):
    def SetVoice(self,voice):
        self.voice = voice
    def Run(self):
        print 'Running'
    

def main():
    #t = CAnimal()
    #t.Say()
    #dog = CAnimal('wow')
    #dog.Say()                  #调用class 1

    bobo = CDog()
    bobo.SetVoice('My name is BOBO')
    bobo.Say()
    bobo.Run()                   ##调用class 2

main()


3、实练

Stock Valuation

A Block of stock has a number of attributes, including apurchase price, purchase date, and number of shares. Commonly, methodsare needed to compute the total spent to buy the stock, and the currentvalue of the stock. A Position is the current ownership ofa company reflected by all of the blocks of stock. APortfoliois a collection ofPositions ; it has methods to computethe total value of allBlocks of stock.

When we purchase stocks a little at a time, each Block hasa different price. We want to compute the total value of the entire set ofBlock s, plus an average purchase price for the set ofBlocks.

The StockBlock class. First, define a StockBlock classwhich has the purchase date, price per share and number of shares. Hereare the method functions this class should have.

StockBlock. __init__ ( self, date, price, number_of_shares )

Populate the individual fields of date, price and number ofshares. This isinformation which is part of thePosition, made up ofindividual blocks.

Don’t include the company name or ticker symbol.

StockBlock. __str__ ( self ) → string
Return a nicely formatted string that shows the date, price and shares.
StockBlock. getPurchValue ( self ) → number
Compute the value as purchase price per share × shares.
Stockblock. getSaleValue ( self, salePrice ) → number
Use salePrice to compute the value as sale price per share × shares.
StockBlock. getROI ( self, salePrice ) → number

Use salePrice tocompute the return on investment as (sale value - purchase value) ÷purchase value.

Note that this is not the annualized ROI. We’ll address this issue below.

#!/usr/bin/env python

class StockBlock(object):
    """ A stock block class which has the purchase date,
        price per share and number of shares. """
    def __init__(self,purchDate,purchPrice,salePrice,shares):  #形参提取database中数据的传递方法值得记住(名字要相同)
        ''' populate the individual fields of date,price,
            and number of shares.'''
        self.date = purchDate
        self.price = purchPrice
        self.saleprice = salePrice
        self.number = shares

    def getPurchValue(self):
        '''compute the value as purchase price per share X shares.'''
        purchvalue = self.price * self.number
        return purchvalue
    
    def getSaleValue(self):
        '''compute the value as price per share X shares.'''
        salevalue = self.saleprice * self.number
        return salevalue
    
    def getROI(self):
        '''computes the return on investment as(sale value - purchase value)/purchase value.'''
        roi = (self.getSaleValue() - self.getPurchValue()) / self.getPurchValue()  #不同def间进行数据交换的方法值得记住
        return roi
    
    def __str__(self):
        '''return a nicely formatted string that shows the
            date,price and shares.'''
        return self.date,self.price,self.number

blocksGM = [
    StockBlock( purchDate='25-Jan-2001', purchPrice=44.89, salePrice=54.32, shares=17 ),
    StockBlock( purchDate='25-Apr-2001', purchPrice=46.12, salePrice=64.34, shares=17 ),
    StockBlock( purchDate='25-Jul-2001', purchPrice=52.79, salePrice=75.32, shares=15 ),
    StockBlock( purchDate='25-Oct-2001', purchPrice=37.73, salePrice=45.35, shares=21 ),
]


def main():
    totalGM = 0
    saleGM = 0
    roiGM = 0
    for s in blocksGM:
        totalGM += s.getPurchValue()
        saleGM += s.getSaleValue()
        roiGM += s.getROI()
        
    print(totalGM)
    print(saleGM)
    print(roiGM)

main()

>>> ================================ RESTART ================================
>>> 
3131.35
4099.37
1.23387211239
>>> 

不同def间进行数据交换的方法值得记住

#!/usr/bin/env python

class Calculate(object):
    """ sum """
    def __init__(self,a,b,c):
        self.a = a
        self.b = b
        self.c = c
        self.ab = 0
        self.bc = 0
        
    def getAB(self):
        ab = self.a * self.b
        return ab
    def getBC(self):
        bc = self.b * self.c
        return bc
    def getABC(self):
        abc = self.getAB() + self.getBC()
        return abc

def main():
    sum = Calculate(2,4,6)
    s = sum.getAB()
    m = sum.getBC()
    t = sum.getABC()
    print s,m,t

main()
>>> ================================ RESTART ================================
>>> 
8 24 32
>>> 

The Position class. A separate class, Position, willhave an the name, symbol and a sequence ofStockBlocks fora given company. Here are some of the method functions this class should have.

Position.

Position. __init__ ( self, name, symbol, * blocks )
Accept the company name, ticker symbol and a collection of StockBlockinstances.
Position. __str__ ( self ) → string
Return a string that contains the symbol, the total number ofshares in all blocks and the total purchse price for all blocks.
Position. getPurchValue ( self ) → number
Sum the purchase values for all of the StockBlocksin this Position. It delegates the hard part of thework to each StockBlock‘s getPurchValue() method.
Position. getSaleValue ( self, salePrice ) → number
The getSaleValue() method requires a salePrice;it sums the sale values for all of the StockBlocks in this Position. It delegates the hard part of the work to each StockBlock‘s getSaleValue() method.
Position. getROI ( self, salePrice ) → number

The getROI() methodrequires asalePrice; it computes the return oninvestment as (sale value - purchase value) ÷ purchase value. Thisis an ROI based on an overall yield.

#!/usr/bin/env python
 
class StockBlock(object):
    """ A stock block class which has the purchase date,
        price per share and number of shares. """
    def __init__(self,date,price,saleprice,number):
        ''' populate the individual fields of date,price,
            and number of shares.'''
        self.date = date
        self.price = price
        self.number = number
        self.saleprice = saleprice
 
    def getPurchValue(self):
        '''compute the value as purchase price per share X shares.'''
        return self.price * self.number
     
    def getSaleValue(self):
        '''compute the value as price per share X shares.'''
        return self.saleprice * self.number
     
    def getROI(self):
        '''computes the return on investment as(sale value - purchase value)/purchase value.'''
        roi = (self.getSaleValue() - self.getPurchValue()) / self.getPurchValue()
        return roi
     
    def __str__(self):
        '''return a nicely formatted string that shows the
            date,price and shares.'''
        return "%s %s %s"%(self.date, self.price, self.number)
 
    def getDate(self):
        return self.date
 
    def getPrice(self):
        return self.price
 
    def getNumber(self):
        return self.number
 
blocksGM = [
    StockBlock('25-Jan-2001', 44.89, 54.23, 17),
    StockBlock('25-Apr-2001', 46.12, 57.34, 17),
    StockBlock('25-Jul-2001', 52.79, 64.23, 15),
    StockBlock('25-Oct-2001', 37.73, 43.45, 21),
]
blocksEK = [
    StockBlock('25-Jan-2001', 35.86, 37.45, 22),
    StockBlock('25-Apr-2001', 37.66, 54.47, 21),
    StockBlock('25-Jul-2001', 38.57, 47.48, 20),
    StockBlock('25-Oct-2001', 27.61, 34.46, 28),
]
 
if __name__ == '__main__':
    totalGM = 0
    for s in blocksGM:
        totalGM += s.getPurchValue()
        print "date: ", s.getDate()
        print "price: ", s.getPrice()
        print "number: ", s.getNumber()
        print "ROI:", s.getROI()
    print totalGM


>>> ================================ RESTART ================================
>>> 
date:  25-Jan-2001
price:  44.89
number:  17
ROI: 0.208064156828
date:  25-Apr-2001
price:  46.12
number:  17
ROI: 0.243278404163
date:  25-Jul-2001
price:  52.79
number:  15
ROI: 0.216707709794
date:  25-Oct-2001
price:  37.73
number:  21
ROI: 0.151603498542
3131.35
>>> 


大致的计算框架总算是完成了!也算实际练习了下class的用法。





posted on 2022-07-05 18:12  我在全球村  阅读(39)  评论(0编辑  收藏  举报