python类创建疑问

假设有 MyName这样一个类
在C++ 中可以用

MyName A,B,C;

一次初始化多个类,在python中应该如何一次创建多个对象呢

可以使用MyName的构造方法直接创建,或者使用locals()函数来创建。

测试代码如下:

参考链接:


https://www.656463.com/wenda/pythonzdylyglzmcshdgdx_61

https://blog.csdn.net/weixin_45564943/article/details/123879858

https://www.e70w.com/hyzs/1517.html



# https://blog.csdn.net/m0_74309242/article/details/128776630
class MyName:  

    def __init__(self,name,age):
        self.name=name
        self.age=age

    def __str__(self):
        return str("姓名:"+self.name+",年龄:"+str(self.age))
    
# https://www.656463.com/wenda/pythonzdylyglzmcshdgdx_61
# 使用构造方法创建对象
pe1=MyName("张三",23)
pe2=MyName("李四",24)
pe3=MyName("王五",25)

print(pe1)
print(pe2)
print(pe3)
print()

#  使用locals()函数创建对象
#  https://blog.csdn.net/weixin_45564943/article/details/123879858
#  https://www.e70w.com/hyzs/1517.html
ps=[]
for i in range(25,30):
    ps.append(locals()['MyName']("路人"+str(i),i))

for pe in ps:
    print(pe)


img