Python字符串和实例对象混淆

2024-06-26 14:54:58 发布

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

在一个类中,在__repr__构造函数中,python对什么是字符串和什么不是字符串感到困惑。这是一个学校项目,别担心,我实际上不会在这里处理社会保险号码。你知道吗

以下代码无效:

def __repr__(self):
    return (
        '\nName:\t'+self.getName()+':\t\t\tNurse\n'+
        '\tPhone:\t\t\t\t\t\t('+str(self.getPhoneNumber())[0:3]+') '+
        str(self.getPhoneNumber())[3:6]+'-'+str(self.getPhoneNumber())[6:10]+'\n'+
        '\tOverseeing Doctor:\t\t\t'+self.getDoctor()+'\n'
        '\tDescription:\t\t\t\t'+self.getDesc()+'\n'+
        '\tBirthday:\t\t\t\t\t'+self.getBDay()+'\n'+
        '\tSocial Security Number:\t\t***-**-'+str(round(self.getSocial()))[5:9]+'\n'+#error is in this line
        str(self._cases[i] for i in range(len(self._cases)))
    )

但是,在另一个类中,我有几乎相同的代码:

def __repr__(self):
    return (
        '\nName:\t'+self.getName()+':\t\t\tDoctor\n'+
        '\tPhone:\t\t\t\t\t\t('+str(self.getPhoneNumber())[0:3]+') '+
        str(self.getPhoneNumber())[3:6]+'-'+str(self.getPhoneNumber())[6:10]+'\n'+
        '\tDepartment:\t\t\t\t\t'+self.getDepartment()+'\n'
        '\tDescription:\t\t\t\t'+self.getDesc()+'\n'+
        '\tBirthday:\t\t\t\t\t'+self.getBDay()+'\n'+
        '\tSocial Security Number:\t\t***-**-'+str(self.getSocial())[5:9]+'\n'+
        str(self._cases)+'\n'
    )

请告诉我两者有什么不同,以及如何修复初始代码。你知道吗


Tags: 字符串代码selfreturndefcasesstrrepr
1条回答
网友
1楼 · 发布于 2024-06-26 14:54:58

您声称此部分有错误:

str(round(self.getSocial()))[5:9]

但是没有告诉我们任何关于您的实际错误的信息;错误伴随着回溯和异常消息,但是如果没有这些详细信息,我们就不能告诉您任何可能出错的信息。可能self.getSocial()返回一个字符串,round()只接受浮点数

>>> round('123')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a float is required

您需要给我们这个错误消息以及您的输入(self.getSocial()的返回值)和预期的输出,这样我们就可以帮助您解决这部分问题;也许您误解了round()的作用。你知道吗

接下来,您将尝试将生成器表达式转换为字符串:

str(self._cases[i] for i in range(len(self._cases))

括号之间的所有内容都是一个延迟求值循环,但是str()不会为您求值。你知道吗

如果要生成一个包含所有大小写的字符串,例如,与tab连接在一起,请改用str.join()

'\t'.join([str(self._cases[i]) for i in range(len(self._cases)])

您真的应该考虑使用^{}模板;它将使改进和可读的代码。你的“工作”示例可以转化为:

def __repr__(self):
    phone = str(self.getPhoneNumber())
    social = str(self.getSocial())
    return (
        '\n'
        'Name:\t{name}:\t\t\tDoctor\n'
        '\tPhone:\t\t\t\t\t\t({phone1}) {phone2}-{phone3}\n'
        '\tDepartment:\t\t\t\t\t{dept}\n'
        '\tDescription:\t\t\t\t{desc}\n'
        '\tBirthday:\t\t\t\t\t{bday}\n'
        '\tSocial Security Number:\t\t***-**-{social}\n'
        '{cases}\n').format(
            name=self.getName(), 
            phone1=phone[:3], phone2=phone[3:6], phone3=phone[6:10],
            dept=self.getDepartment(), desc=self.getDesc(),
            bday=self.getBDay(), social=social[5:9],
            cases=self._cases)

相关问题 更多 >