所以,如果你想从类中创建一个对象:
class person:
pass
myObj=person()
但是如果你想创建大量的对象呢?我总是收到姓名错误:
In [1]: class person(object):
...: pass
...:
In [2]: for name in [khalid, majid]:
...: name=person()
...:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-2-425dbd385d30> in <module>()
----> 1 for name in khalid, majid:
2 name=person()
3
NameError: name 'khalid' is not defined
那么,为什么会这样呢?
答案 0 :(得分:1)
这不起作用,因为当你写:
for name in [khalid, majid]:
Python尝试查找名称khalid
和majid
,因此列表也可以引用它们引用的对象。但这些名称尚未分配,因此NameError
。
执行此操作的最佳方法是使用name
字符串作为键创建对象词典:
people = {}
for name in ["khalid", "majid"]:
people[name] = person()
您还可以将name
设为实例属性:
class Person(object): # upper case for class names is conventional
def __init__(self, name):
self.name = name
和/或将对象放在列表中:
people = []
for name in ["khalid", "majid"]:
people.append(Person(name))