gpt4 book ai didi

python - 打印和格式化实例

转载 作者:太空宇宙 更新时间:2023-11-04 05:11:28 24 4
gpt4 key购买 nike

我试图在此处为此类定义一个str 方法,以便在打印 Student 类的实例时,它会打印以下格式的内容:我的名字是 ___。我上大学已经 __ 年了,我编写了 __ 程序。在正确的措辞下方是打印,但正确的值未打印。任何帮助将不胜感激。

class Student():
def __init__(self, name, years_at_umich=1):
self.name = name
self.years_UM = years_at_umich
self.bonus_points = random.randrange(1000)
self.programs_written = 0
def __str__(self):
return "My name is %s. I've been in college for %d years and I've written %d programs" \
%(self.name, self.years_UM, self.programs_written)
def shout(self, phrase_to_shout):
print phrase_to_shout

def year_at_umich(self):
return self.years_UM

def write_programs(self, progs=1):
self.programs_written += progs
return self.programs_written

*** 测试不同的值,目前它只通过了学生 4 的最后一次测试********

class Student_test(unittest.TestCase):
def test_student1(self):
student1 = Student("Lyra")
self.assertEqual(student1.__str__(),"My name is Lyra. I've been at UMich for 1 years and I've written 0 programs.")
def test_student2(self):
student2 = Student("Aisha")
student2.write_programs()
self.assertEqual(student2.__str__(),"My name is Aisha. I've been at UMich for 1 years and I've written 1 programs.")
def test_student3(self):
student3 = Student("Ali",3)
student3.write_programs(4)
self.assertEqual(student3.__str__(),"My name is Ali. I've been at UMich for 3 years and I've written 4 programs.")
def test_student4(self):
student4 = Student("Aja")
student4.write_programs(12)
self.assertEqual(student4.programs_written, 12)
student4.write_programs()
self.assertEqual(student4.programs_written,13)

最佳答案

class Student():
def shout(num, word):
if num == 1:
phrase = "My name is %s" % word
elif num == 2:
phrase = "I love %s" % word
elif num == 3:
phrase = "My favorite food is %s" % word
return phrase

def years(num):
phrase = "I've been at umich for %s years" % num
return phrase

def programs(num):
phrase = "I've written %s programs" % num
return phrase

Student.shout(1, 'Mud')
'My name is Mud'

关于python - 打印和格式化实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42882186/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com