python之类和__init__

构建一个商品类,__init__函数类似于构造方法,self类似于this


1 import random
2 class Goods:
3     def __init__(self, name, price):
4         self.name = name
5         self.price = price
6 
7     def changeprice(self, m, n):
8         self.price = random.randint(m, n)
9         return self.price

再写一个商店类,用于存放商品

 1 class Gshop:
 2     goodslist = []
 3     def __init__(self, g):
 4         self.goodslist.append(g)
 5 
 6     def add(self, g):
 7         self.goodslist.append(g)
 8 
 9     def changegoodslistprice(self):
10         for w in self.goodslist:
11             w.changeprice(20, 50)
12             print(w.name, w.price)

 

实例化对象,执行对象的方法


1 import goods,gshop
2 toy = goods.Goods('洋娃娃', 30)
3 gshopdemo = gshop.Gshop(toy)
4 #print(toy.name, toy.price)
5 
6 car_wlhg = goods.Goods('五菱宏光', 30000)
7 gshopdemo.add(car_wlhg)
8 gshopdemo.changegoodslistprice()

运行结果:

python之类和__init__ - 星瑞 - 星瑞的博客
posted @ 2017-07-23 09:11  星瑞  阅读(315)  评论(0编辑  收藏  举报