python之類和__init__
阿新 • • 發佈:2017-07-23
return clas self his 技術分享 一個 -i chang end
構建一個商品類,__init__函數類似於構造方法,self類似於this
import random
class Goods:
def __init__(self, name, price):
self.name = name
self.price = price
def changeprice(self, m, n):
self.price = random.randint(m, n)
return self.price
再寫一個商店類,用於存放商品
class Gshop:
goodslist = []
def __init__(self, g):
self.goodslist.append(g)
def add(self, g):
self.goodslist.append(g)
def changegoodslistprice(self):
for w in self.goodslist:
w.changeprice(20, 50)
print(w.name, w.price)
實例化對象,執行對象的方法
import goods,gshop
toy = goods.Goods(‘洋娃娃‘, 30)
gshopdemo = gshop.Gshop(toy)
#print(toy.name, toy.price)
car_wlhg = goods.Goods(‘五菱宏光‘, 30000)
gshopdemo.add(car_wlhg)
gshopdemo.changegoodslistprice()
運行結果:
python之類和__init__