# 类属性与方法的使用
class Goods:
id_count = 0
# 装饰器写法,@class method用来定义类方法
@classmethod
def generate_id(cls):
cls.id_count += 1
return cls.id_count
def __init__(self):
# 商品的唯一序号,00001,00002,使用zfill函数将整数转化为5位的字符串
self.id = str(self.generate_id()).zfill(5)
self.name = ''
self.price = 0
self.discount = 1
# 每次创建一个实例,就生成一个编号
g1 = Goods()
print(g1.id)
g2 = Goods()
print(g2.id)
g3 = Goods()
print(g3.id)
# 使用for循环创建多个实例
for _ in range(10):
g = Goods()
print(g.id)
print(Goods.id_count)
运行结果:
C:\Users\dnxxb\PycharmProjects\pythonProject\venv\Scripts\python.exe C:\Users\dnxxb\PycharmProjects\pythonProject\goods.py
00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
13
标签:count,Goods,Python,self,print,cls,方法,id,属性 From: https://www.cnblogs.com/kemilee/p/17681145.html