Python 2.7:如何在另一个类中使用一个类的对象?
问题描述:
我在蟒蛇比较新,我试图完成以下任务:Python 2.7:如何在另一个类中使用一个类的对象?
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类的对象。然后我想将这些对象追加到列表中。有人可以告诉我如何做到这一点?
答
不知道如果我理解你,但是,假设你有从用户已收集的名单:
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
+0
不会像B类(A类):在B类申报中被要求吗? – Janmajay
+0
@Janmajay不,没有必要。 '类A'在模块范围内,所以它可以从'B类'内部看到。 – TisteAndii
什么是名称和L1? –
我投票结束这个问题作为题外话,因为SO既不是一个编码服务,也不是一个家庭作业完成服务。 – TigerhawkT3
@ TigerhawkT3,你怎么知道它是作业? –