python之类和__init__

时间:2023-03-08 22:54:29
python之类和__init__

构建一个商品类,__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__