在下面的参加者类中,您定义了 setter,每当创建对象并且用户输入数据时,它将为您的数据属性(变量)设置值
并且您还定义了用于按需检索这些数据的 getter
最后一行str将对象状态打印为字符串
class Attendee:
def __init__(self, fName, lName, email):
self.fName = fName
self.lName = lName
self.email = email
def set_fName(self, fName):
self.__fName = fName
def set_lName(self, lName):
self.__lName = lName
def set_email(self, email):
self.__email = email
def get_fName(self, fName):
return self.__fName
def get_lName(self, lName):
return self.__lName
def get_email(self, email):
return self.__email
def __str__(self):
return "First name: " + self.__fName + "\nLast name: " + self.__lName + "\nEmail: " + self.__email
下面是一个主程序的示例,它要求用户输入并创建一个类对象(New_attendee 类)我添加了一个字典,它首先创建为空(= {})并且每个条目都存储在字典中
def main():
NewAttendee = {}
again = 'y'
while again == 'y':
fName = input("First name: ")
lName = input("Last name: ")
email = input("Email: ")
entry = Attendee(fName,lName, email)
if fName not in NewAttendee:
NewAttendee[fName] = entry
print('The new attendee has been added')
else:
print('That name already exists.')
again = input('Do you want to add a new attendee? \'y\' for yes -->')
main()
希望有帮助!PS:我没有把str(对象状态作为字符串)付诸行动