python3动物分类中的写作方法

2024-10-01 22:31:20 发布

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

我需要构建一个类来描述一个未知的灭绝动物种族(称为AnimalX)。 每个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

这是为了确保当我们在实例化AnimalX对象时没有为has_horns参数提供参数时,它的has\horns属性会自动设置为False。你知道吗

使用AnimalX类,我需要编写两个方法:

   say_hello(): it prints "Hi! The name is {name}!. 

如果AnimalX有角,请在所有大写字母中打印

   say_hello(): it prints "HI! THE NAME IS {NAME}

我有一个基本的了解如何写方法,但以上是驱动我疯狂。。。我需要关于如何写上述两种方法的建议。你知道吗

 Test Case:                                       Output
  first_AnimalX = AnimalX("Jeff", 1.6)
  first_AnimalX.say_hello()                    Hi! My name is Jeff!

Tags: of方法nameselffalsehello参数type
1条回答
网友
1楼 · 发布于 2024-10-01 22:31:20

只需编写一个方法即可获得所需的行为:

def say_hello(self):
    phrase = 'Hi! The name is ' + self.name + '!'
    print(phrase.upper() if self.has_horns else phrase)

我猜在所有大写字符串的末尾缺少'!'是一个打字错误。如果不是,请使用phrase.upper()[:-1]

相关问题 更多 >

    热门问题