我想做一个搜索程序,但不知道如何打印用户名和全名

2024-03-29 09:17:29 发布

您现在位置:Python中文网/ 问答频道 /正文

import datetime

tday = datetime.date.today()
username =input('input something:')


class person:
    def __init__(self, first, last, ip, birtyear, birthmonth, birthday):
        self.first = first
        self.last = last
        self.ip = ip
        self.birthyear = birtyear
        self.birthmonth = birthmonth
        self.birthday = birthday
    def fullname(self):
        return '{} {}'.format(self.first, self.last)
    def yearage(self):
          return '{}'.format(tday.year - self.birthyear)
    def monthage(self):
          return '{}'.format(tday.month - self.birthmonth)
    def dayage(self):
          return '{}'.format(tday.day - self.birthday)
    def birth(self):
        b1 = self.birthmonth, self.birthday,
        b2 = self.birthyear
        return'{} {}'.format(b1, b2)
    def ip1(self):
        return'{}'.format(self.ip)


names = ['x1', 'x2']

x1 = person('x1', 'y1', 50000, 2002, 2, 22)
x2 = person('x2', 'y2', 60000, 2004, 4, 24)

flag = 0
for i in names:
    if (i==username):
        print ((username).fullname())
        flag=1
        break

if (flag == 0):
    print("element not found")

2条回答

username只是用户作为输入提供的字符串。 因此,它没有为person类实现的函数fullname()

我不知道你的目标是什么,你可以在最后打印硬编码的"x1 y2",或者只回复用户输入的内容

您需要将您的人员添加到列表中,以便在其中进行搜索。仅仅因为您有一个名为x1的变量,并不意味着您可以使用(username).fullname()来引用该变量。Python不是这样工作的

names = [
    person('x1', 'y1', 50000, 2002, 2, 22)
    person('x2', 'y2', 60000, 2004, 4, 24)
]

flag = 0
for user in names:
    if user.first == username:
        print( user.first, user.fullname())
        flag=1
        break

if flag == 0:
    print("element not found")

相关问题 更多 >