我正在尝试使用我创建的两个列表的入口创建我的类Member
的对象:
class Member:
__name = ""
__dayoff = ""
amount = int(input()) #amount of members
peplist = [] #list with all the names
dolist = [] #list with all the days off
for i in range(0, amount):
print('\n')
print('type in a persons name please!')
name = input()
peplist.append(name)
daycheck()
我的功能daycheck()
如下所示:
def daycheck():
print('type in', name, "'s day off, please!")
dayoff = input()
if (dayoff == 'monday') or (dayoff == 'tuesday') or (dayoff == 'wednesday') or (dayoff == 'thursday') or (dayoff == 'friday') or (dayoff == 'saturday') or (dayoff == 'sunday'):
print(name, "'s dayoff is", dayoff, '!!!')
dolist.append(dayoff)
else:
print("I don't know this day! Please try again!")
daycheck()
现在想要创建一个我的类Member()的对象,其中包含两个列表中的属性name
和dayoff
,例如:
for i in range(0, amount):
Member[i] = Member(peplist[i], dolist[i])
显然,这个for循环不起作用,但有没有办法用这样的属性表单创建对象?
答案 0 :(得分:0)
我认为这应该更接近你的意图:
class Member:
def __init__(self, name, dayoff):
self.name = name
self.dayoff = dayoff
peplist = ['A', 'B', 'C']
dolist = ['monday', 'tuesday', 'thursday']
members = [Member(name, dayoff) for name, dayoff in zip(peplist, dolist)]
让我们看一下里面的内容:
for member in members:
print(member.name, member.dayoff)
打印:
A monday
B tuesday
C thursday
此功能daycheck
可以更好地运作:
def daycheck(name, dolist):
days = ['monday', 'tuesday', 'wednesday','thursday', 'friday',
'saturday', 'sunday']
print('type in', name, "'s day off, please!")
dayoff = input()
if dayoff.strip().lower() in days:
print(name, "'s dayoff is", dayoff, '!!!')
dolist.append(dayoff)
else:
print("I don't know this day! Please try again!")
daycheck(name, dolist)
daycheck('A', dolist)