首页 > 编程语言 >关于python class

关于python class

时间:2022-10-13 22:02:07浏览次数:43  
标签:__ python self number price 关于 class def

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

. When getValue()adds 1, the value is in the usual range for a single die,

.



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

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

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 salePrice StockBlock. getROI ( self, salePrice

) → number

Use salePrice

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.'''
saleval(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

Position.


Position. __init__ ( self, name, symbol, * blocks

) 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 StockBlocksin this Position. It delegates the hard part of thework to each StockBlock‘s getPurchValue() Position. getSaleValue ( self, salePrice

) → number 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() 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的用法。






标签:__,python,self,number,price,关于,class,def
From: https://blog.51cto.com/u_15797945/5754734

相关文章

  • python算法简介与各种生成式
    今日内容概要算法简介及二分法三元表达式各种生成式匿名函数重要内置函数常见内置函数今日内容详细算法简介及二分法1.什么是算法 算法就是解决问题的有校......
  • python函数及算法
    算法二分法二分算法图什么是算法?​ 算法是高效解决问题的办法。需求:有一个按照从小到大顺序排列的数字列表,查找某一个数字#定义一个无序的列表nums=[3,4,5,67,......
  • python爬虫爬取国家科技报告服务系统数据,共计30余万条
    python爬虫爬取国家科技报告服务系统数据,共计30余万条按学科分类【中图分类】共计三十余万条科技报告数据爬取的网址:​​https://www.nstrs.cn/kjbg/navigation​​!!!分析网站......
  • python使用xml.dom.minidom写xml节点属性会自动排序问题解决
    1.背景及问题一个xml文件,过滤掉部分节点,生成新的xml文件,但是生成后,发现节点的属性顺序变化了,根据key的字母信息排了序。如原始信息:<stringtypename="time_type"length......
  • 关于背包
    关于背包:背包的本质是每一个物品或动作对当前所有状态的更新板子:01背包:#include<iostream>#include<algorithm>usingnamespacestd;constintN=1010;......
  • python常见的运算符及用法
    ✅个人主页:​​hacker_demo的51CTO博客......
  • Python 深度学习目标检测评价指标
    目标检测评价指标:准确率(Accuracy),混淆矩阵(ConfusionMatrix),精确率(Precision),召回率(Recall),平均正确率(AP),meanAveragePrecision(mAP),交除并(IoU),ROC+AUC,非极大值抑制(NMS)。假......
  • mac os python安装问题
    首先直接下载官网安装包安装https://www.python.org/downloads/ 然后配置环境变量#打开~/.bash_profilevim~/.bash_profile#写入环境变量,保存exportPATH="/......
  • 【python 游戏】闲的无聊?那就和博主一起来滑雪吧~
    前言嗨喽~大家好呀,这里是魔王呐!  滑雪运动(特别是现代竞技滑雪)发展到当今,项目不断在增多,领域不断在扩展。世界比赛正规的大项目分为:高山滑雪、北欧滑雪(NordicSk......
  • Python--ctypes(数据类型详细踩坑指南)
    pthon--ctypes包装C语言数据类型一.ctypes使用介绍ctypes是Python的外部函数库。它提供了与C兼容的数据类型,并允许调用DLL或共享库中的函数。可使用该模块以......