Python 2.7:如何在另一个类中使用一个类的对象?

时间:2016-03-05 00:57:51

标签: python object

我在python上比较新,我正在努力完成以下任务:

class A:
       def __init__(self,name,L1):  
       self.name=name
       self.L1=[0,0]

class B:
    def __init__(self, person_names):
    #this is where person_names are entered in the program
    #person_names is used as object parameter while creating objects of class A

我想使用用户输入的名称在B中创建A类对象。然后我想将这些对象附加到列表中。有人可以告诉我如何做到这一点?

1 个答案:

答案 0 :(得分:0)

不确定我是否理解你,但假设你已经从用户那里收集了名单:

class B:
    def __init__(self, person_names):
        self.objs = []  # list to contain objs
        for name in person_names:
            self.objs.append(A(name))  # create class A object and add to list

OR

    class B:
        def __init__(self):
            self.objs = []  # list to contain objs
            while True:
                name = input('Enter a name: ')
                if not name: break   # empty string signals end of input
                self.objs.append(A(name))  # create class A object and add to list