Skip to content

python面向对象

ChannelCMT edited this page Jun 3, 2019 · 1 revision

Python面向对象

1、 什么是对象

属性+方法=类

同一个类可以生成无数个对象

一只股票的属性: 市值,成交量,价格...

方法: 获取股票的市值、成交量,计算成交额

2、 通常命名方式

  • 类名用大写
  • 属性为名词
  • 方法为动词
class StockA:
    price=20
    volume=10000
    def calAmount():
        return price*volume

# 实例化类对象
checkStockA = StockA()
checkStockA.calAmount()
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-2-89ad93b50f09> in <module>()
      7 # 实例化类对象
      8 checkStockA = stockA()
----> 9 checkStockA.calAmount()


TypeError: calAmount() takes 0 positional arguments but 1 was given

3、 self

类方法必须包含参数 self,且为第一个参数,隐藏并默认的要求。

class StockA:
    marketvalue=50000
    price=20
    volume=10000
    def calAmount(self):
        return self.price*self.volume

# 实例化类对象
checkStockA = StockA()
checkStockA.calAmount()
200000

4、 一个类生成多个对象

class stock:
    def getToday(self,stockName, price, volume):
        self.stockName=stockName
        self.price = price
        self.volume = volume
    def calAmount(self):
        return {self.stockName+'_Amount': self.price*self.volume}

# 实例化类创建类对象
stockBABA = stock()
stockBABA.getToday('BABA', 180, 30000)
print(stockBABA.calAmount())

stockTencent = stock()
stockTencent.getToday('Tencent', 350, 20000)
print(stockTencent.calAmount())

stockBIDU = stock()
stockBIDU.getToday('BIDU', 230, 10000)
print(stockBIDU.calAmount())
{'BABA_Amount': 5400000}
{'Tencent_Amount': 7000000}
{'BIDU_Amount': 2300000}

5、init

实例化时自动运行

class stock:
    def __init__(self,stockName, price, volume):
        self.stockName=stockName
        self.price = price
        self.volume = volume
    def calAmount(self):
        return {self.stockName+'_Amount': self.price*self.volume}

stockBABA = stock('BABA', 180, 30000)
print(stockBABA.calAmount())

stockTencent = stock('Tencent', 350, 20000)
print(stockTencent.calAmount())

stockBIDU = stock('BIDU', 230, 10000)
print(stockBIDU.calAmount())
{'BABA_Amount': 5400000}
{'Tencent_Amount': 7000000}
{'BIDU_Amount': 2300000}

6、 公有/私有变量

# 公有变量名

class stockBABA:
    name = 'BABA'
stockName = stockBABA()
stockName.name
'BABA'
# 私有变量名
class stockBABA:
    __name = 'BABA'
stockName = stockBABA()
stockName.__name
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-24-aa8ac6c7289a> in <module>()
      3     __name = 'BABA'
      4 stockName = stockBABA()
----> 5 stockName.__name


AttributeError: 'stockBABA' object has no attribute '__name'
# 伪私有变量名: _类名__变量名

class stockBABA:
    __name = 'BABA'
stockName = stockBABA()
stockName._stockBABA__name
'BABA'
Clone this wiki locally