python之类和__init__
Python __ init 之类
2023-09-11 14:19:57 时间
构建一个商品类,__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__ - 星瑞 - 星瑞的博客](http://img2.ph.126.net/1Lk6NaHGyoIq5j9pKI-ibg==/6632602683932879162.jpg)
相关文章
- Python内置函数——__import__ 的使用方法
- 【华为OD机试真题 python】 组成最大时间【2022 Q4 | 100分】
- python 中的__init__.py的用法与个人理解
- python遇到的知识点
- notepad++中设置python运行
- python中self.__class__的用法详解
- 学python能做什么兼职-初学Python到月入过万最快的兼职途径(纯干货)
- 【python实战】拒绝黄牛!我要用python原价冲周董演唱会~Python自动秒杀抢票脚本
- Python 中的3Dplot
- python基础——使用__slots__
- 136 python高级 - 正则表达式(匹配分组)
- 18 python - 列表
- gyp ERR! stack Error: Can‘t find Python executable “python“, you can set the PYTHON env variable.
- python中 __init__.py的例程
- 《Python面向对象编程指南》——1.5 通过工厂函数调用__init()__
- 《Python面向对象编程指南》——1.6 在每个子类中实现__init()__方法
- python 中 open与with open 的区别
- 【转载】python的魔法方法———A Guide to Python's Magic Methods
- 华为OD机试 - 时间格式化(Python) | 机试题+算法思路+考点+代码解析 【2023】
- 用python 做了一个 自动录视频软件, 可以去水印,可以随时暂停,可调用免费语音引擎,可以自由控制, 做视频教学的话非常方便。
- 【Python基础】我的第一个 python 程序
- Unity 工具 之 报错 Jenkins 执行/调用 Python 脚本,报错提示 ‘python‘ 不是内部或外部命令,也不是可运行的程序或批处理文件
- 【Python】python 库分类大全
- 详细解读Python中的__init__()方法
- Python每日一学 06——while循环
- python 类的创建和使用
- python__init__的作用