You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3中AnimalX类say_hello方法编写技术求助

没问题,这事儿简单!我帮你把say_hello方法加上,完美匹配你的需求。

首先,先修正你原来代码里的小疏漏(class AnimalX后面缺了冒号,文档字符串的格式也调整得更规范了),然后加上对应的方法逻辑:

class AnimalX:
    """Defines the AnimalX class. 
    Data attributes: 
        name of type str 
        height (metres) of type float 
        has_horns of type bool 
    """
    def __init__(self, name, height, has_horns=False):
        """AnimalX constructor"""
        self.name = name
        self.height = height
        self.has_horns = has_horns

    def say_hello(self):
        # 根据是否有角判断输出格式
        if self.has_horns:
            # 有角时全大写输出
            print(f"HI! MY NAME IS {self.name.upper()}!")
        else:
            # 无角时正常格式输出(匹配你的测试用例)
            print(f"Hi! My name is {self.name}!")

逻辑解释:

  • say_hello是实例方法,必须带self参数,这样才能访问每个AnimalX实例的name和has_horns属性
  • 直接用if self.has_horns:判断即可,因为has_horns本身就是布尔值,不用多此一举写== True
  • 用f-string来拼接字符串,简洁又清晰:有角的时候把名字转成大写(self.name.upper()),同时整个问候语也写成全大写;无角的时候就用你测试用例里的正常格式

测试验证:

运行你给的测试用例:

first_AnimalX = AnimalX("Jeff", 1.6)
first_AnimalX.say_hello()

输出正好是:Hi! My name is Jeff!

再测试一个有角的实例:

spiky_animal = AnimalX("Rex", 2.5, has_horns=True)
spiky_animal.say_hello()

输出会是:HI! MY NAME IS REX!

对了,我注意到你描述里写的无角输出是Hi! The name is {name}!,但测试用例里是Hi! My name is Jeff!,我按照测试用例的格式写了,如果需要改成The,只需要把else分支里的字符串改成f"Hi! The name is {self.name}!"就行~

内容的提问来源于stack exchange,提问作者user9762260

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:23:11