方法一:
class Blog:
def __init__(self,num):
print("a new object num is",num)
self.value = num
def __str__(self):
return str(self.value+3)
# 循环建立四个对象,locals()函数可以将字符串转换为变量名!
#具体的操作和含义我并不清楚,大家可以自行百度~
for i in range(1,5):
locals()['blog_'+str(i)] = Blog(i)
#验证是否有blo_3这个对象变量
print(blog_3)
效果:
('a new object num is', 1)
('a new object num is', 2)
('a new object num is', 3)
('a new object num is', 4)
3
方法二:(用的较多)
class bianyuan(custom):
cj = 430080
def __init__(self, name, data, cj):
super(bianyuan, self).__init__(name)
self.cj = cj
self.data = data
def distribute(self, slip):
self.data = self.data + slip
flag = 1 ##设置flag,用于批量命名对象
for name in m_qos_suit_keys:
# for i in range(1,101):
if flag<101:
locals()["bianyuan_"+str(flag)] = bianyuan(name, 0, m_limit.get(name)) ##批量命名对象
flag += 1
bianyuan_1.distribute(slip)
bianyuan_2.distribute(slip)
bianyuan_3.distribute(slip)
print(bianyuan_1.data)
print(bianyuan_1.name)
print(bianyuan_2.data)
print(bianyuan_2.name)